目录
1,题目描述
- palindrome:回文数;
Sample Input 1:
97152
Sample Output 1:
97152 + 25179 = 122331
122331 + 133221 = 255552
255552 is a palindromic number.
Sample Input 2:
196
Sample Output 2:
196 + 691 = 887
887 + 788 = 1675
1675 + 5761 = 7436
7436 + 6347 = 13783
13783 + 38731 = 52514
52514 + 41525 = 94039
94039 + 93049 = 187088
187088 + 880781 = 1067869
1067869 + 9687601 = 10755470
10755470 + 07455701 = 18211171
Not found in 10 iterations.
题目大意
判断一个数在10次操作(将这个数字与逆序的数字相加,并将结果作为新的数字)之内能否变为回文数。
2,思路
1,bool isPalindrome(string s):判断数字(字符串形式)是否为回文数;
2,string add(string a):迭代操作,a与a的逆序相加;
3,AC代码
#include<bits/stdc++.h>
using namespace std;
bool isPalindrome(string s){
int i = 0, j = s.size()-1;
while(i < j && s[i] == s[j]){
i++;j--;
}
if(i < j) return false;
else return true;
}
string add(string a){
string b = a, c = ""; //c = a + b
reverse(b.begin(), b.end());
int carry = 0;
for(int i = a.size()-1; i >= 0; i--){
int tem = (a[i]-'0') + (b[i]-'0') + carry;
if(tem >= 10){ // !!!>=
tem -= 10;
carry = 1;
}else carry = 0;
c += ('0' + tem);
}
if(carry == 1) c += '1';
reverse(c.begin(), c.end());
cout<<a<<" + "<<b<<" = "<<c<<endl;
return c;
}
int main(){
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
string s;
cin>>s;
int step = 10;
while(step--){
if(isPalindrome(s)){
cout<<s;
printf(" is a palindromic number.");
return 0;
}
s = add(s);
}
printf("Not found in 10 iterations.");
return 0;
}
4,解题过程
一发入魂o(* ̄▽ ̄*)ブ