1136 A Delayed Palindrome (20 分)
题目大意
大整数运算,直接看测试样例就能知道题意。
基本思路
1 将字符串倒置与原字符串比较看是否相等可知s是否为回文串
2 字符串s和它的倒置t相加,只需从头到尾相加然后再倒置(记得要处理最后一个进位carry,如果有进位要在末尾+’1’)
3 倒置可采用algorithm头文件里面的函数reverse(s.begin(), s.end())直接对s进行倒置
代码
#include <bits/stdc++.h>
using namespace std;
string add(string a,string b){
string ans;//结果串
int carry=0;//进位
//大整数运算
for (int i = 0; i < a.length(); ++i) {
int num=(a[i]-'0'+b[i]-'0')+carry;
carry=0;
if(num>=10){
num=num-10;
carry=1;
}
ans=ans+char((num+'0'));//1+‘0’-->49 char(49)--'1'
}
//考虑最高位的进位
if(carry==1){
ans=ans+'1';
}
//反转最后的结果并输出
reverse(ans.begin(),ans.end());
return ans;
}
int main(){
string s;//始终作为每一次循环的初始串
cin>>s;
for (int i = 0; i < 10; ++i) {
string t=s;
reverse(t.begin(),t.end());
//如果字符串s就是(s==t)就是回文串,输出"s is a palindromic number.",返回
//否则,输出计算s和t和的过程,更新s
if(t==s){
cout<<s<<" is a palindromic number."<<endl;
return 0;
}else{
string tsum=add(s,t);
cout<<s<<" + "<<t<<" = "<<tsum<<endl;
s=tsum;
}
}
//到了这一步,说明10步之内没有回文数,输出 "Not found in 10 iterations."
cout<< "Not found in 10 iterations."<<endl;
return 0;
}