目錄
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(* ̄▽ ̄*)ブ