問題描述
123321是一個非常特殊的數,它從左邊讀和從右邊讀是一樣的。
輸入一個正整數n, 編程求所有這樣的五位和六位十進制數,滿足各位數字之和等於n 。
輸入格式
輸入一行,包含一個正整數n。
輸出格式
按從小到大的順序輸出滿足條件的整數,每個整數佔一行。
樣例輸入
52
樣例輸出
899998
989989
998899
數據規模和約定
1<=n<=54。
剛開始,我是想把這個5位數反向存到字符串中,再把字符串化成整型,然而在string轉換int的過程中卡住了,atoi總是會報錯。最後問了大神 使用了sstream才解決了。
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
int n;
cin>>n;
int str=10001;
//int str;
//if(n<=45)
// str=10001;
//else if(n>46)
// str=100001;
for(str;str<=999999;str++)
{
string st="";
int x=0;
int t=str;
while(t!=0)
{
st+=t%10+'0';
x+=t%10;
t/=10;
}
if(x==n)
{
int temp;
stringstream ss;
ss<<st;
ss>>temp;
if(str==temp)
cout<<str<<endl;
else continue;
}
else continue;
}
return 0;
}
然而,超時了,當時我就懵逼了…
後來百度之後,換了種方法
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int i;
if(n<=45)
i=10001;
else if(n>45)
i=100001;
for(i;i<=999999;i++)
{
int a,b,c,d,e,f;
a=i/100000;
b=(i%100000)/10000;
c=(i%10000)/1000;
d=(i%1000)/100;
e=(i%100)/10;
f=i%10;
int x;
x=a+b+c+d+e;
if(x==n)
{
if(a==0)
{
if(b==f&&c==e)
cout<<i<<endl;
else continue;
}
else
{
if(a==f&&b==e&&c==d)
cout<<i<<endl;
else continue;
}
}
else continue;
}
return 0;
}
但是結果顯示錯誤,然而我自己調試都是沒問題的,當時我的內心簡直就是千萬只草泥馬奔騰而過…
最後嘗試優化一下第一次的代碼
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main()
{
int n;
cin>>n;
int str;
if(n<=45)
str=10001;
else if(n>46)
str=100001;
for(str;str<=999999;str++)
{
string st="";
int x=0;
int t=str;
while(t!=0)
{
st+=t%10+'0';
x+=t%10;
t/=10;
}
if(x==n)
{
int temp;
stringstream ss;
ss<<st;
ss>>temp;
if(str==temp)
cout<<str<<endl;
else continue;
}
else continue;
}
return 0;
}
總算勉強通過了…只是直到我寫這篇博客,還是沒搞懂第二遍提交的代碼問題出在哪裏…