1079 延迟的回文数 - PAT (Basic Level) Practice (中文) (pintia.cn)
如果只是按照题意思正常写,会有一个测试点过不去:
#include<bits/stdc++.h>
using namespace std;
int main()
{
int cnt=0;
string s1,s2;cin>>s1;
string temp=s1;
reverse(temp.begin(),temp.end());
if(s1==temp) //给的字符串直接就是回文数的情况
{
cout<<s1<<" is a palindromic number."<<endl;
}
else
{
while(true)
{
if (cnt >= 10)
{
cout << "Not found in 10 iterations." << endl;
break;
}
s2=s1;
reverse(s2.begin(),s2.end());
int num1=stoi(s1);
int num2=stoi(s2);
int sum=num1+num2;
cout<<s1<<" + "<<s2<<" = "<<sum<<endl;
cnt++;
string str_sum=to_string(sum);
string temp=str_sum;
reverse(temp.begin(),temp.end());
if(str_sum==temp)
{
cout<<str_sum<<" is a palindromic number."<<endl;
break;
}
else
{
s1=str_sum;
}
}
}
return 0;
}
这是因为有进位的存在,我们需要模拟一下加法:
注意模拟加法的话我们要从低位开始相加,即倒着相加,不然的话结果不准确:
#include<bits/stdc++.h>
using namespace std;
string add(string s1, string s2)
{
string s = s1;
int carry = 0;
for (int i = s1.size() - 1; i >= 0; i--) //从个位开始相加
{
s[i] = ((s1[i] - '0') + (s2[i] - '0') + carry) % 10 + '0';
carry = ((s1[i] - '0') + (s2[i] - '0') + carry) / 10;
}
if (carry > 0)
{
s = "1" + s;
}
return s;
}
int main()
{
int cnt=0;
string s1,s2;cin>>s1;
string temp=s1;
reverse(temp.begin(),temp.end());
if(s1==temp)
{
cout<<s1<<" is a palindromic number."<<endl;
}
else
{
while(true)
{
if (cnt >= 10)
{
cout << "Not found in 10 iterations." << endl;
break;
}
s2=s1;
reverse(s2.begin(),s2.end());
string sum=add(s1,s2);
cout<<s1<<" + "<<s2<<" = "<<sum<<endl;
cnt++;
string str_sum=sum;
string temp=str_sum;
reverse(temp.begin(),temp.end());
if(str_sum==temp)
{
cout<<str_sum<<" is a palindromic number."<<endl;
break;
}
else
{
s1=str_sum;
}
}
}
return 0;
}
注意add()函数里面让s=s1的目的是为了让s和s1等长,如果不加这句话s就没有办法完全存下s1+s2的结果。
当然也可以把这句话换为:
s.resize(s1.size());
效果是一样的。