solution
给出的整数不超过1000位且涉及加法运算,需要用到大数加法(按位相加),而测试点6正是大数测试用例
#include<iostream>
#include<string>
using namespace std;
bool isPali(string s){//是否为回文串
for(int i = 0; i <= s.size() / 2; i++){
if(s[i] != s[s.size() - i - 1]) return false;
}
return true;
}
int main(){
string s, t, sum;
int cnt = 10, carry;
cin >> s;
while(cnt--){
if(isPali(s)){//是回文串且操作次数不大于10,则属于延迟回文串
cout << s << " is a palindromic number.";
return 0;
}
t = "";
sum = s;//!初始化sum
carry = 0;
for(int i = s.size() - 1; i >= 0; i--){
t += s[i];
}
for(int i = s.size() - 1; i >= 0; i--){//1000位,大数相加
sum[i] = (s[i] - '0' + t[i] - '0' + carry) % 10 + '0';
carry = (s[i] - '0' + t[i] - '0' + carry) / 10;
}
if(carry) sum = "1" + sum;//最高位进位
cout << s << " + " << t << " = " << sum << endl;
s = sum;
}
cout << "Not found in 10 iterations.";
return 0;
}
或者
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
bool isPali(string s){
for(int i = 0; i <= s.size() / 2; i++){
if(s[i] != s[s.size() - i - 1]) return false;
}
return true;
}
int main(){
string s, t, sum;
int cnt = 10, carry;
cin >> s;
while(cnt--){
if(isPali(s)){
cout << s << " is a palindromic number.";
return 0;
}
t = sum = s;
carry = 0;
reverse(t.begin(), t.end());
for(int i = s.size() - 1; i >= 0; i--){//1000位,大数相加
sum[i] = (s[i] - '0' + t[i] - '0' + carry) % 10 + '0';
carry = (s[i] - '0' + t[i] - '0' + carry) / 10;
}
if(carry) sum = "1" + sum;//最高位进位
cout << s << " + " << t << " = " << sum << endl;
s = sum;
}
cout << "Not found in 10 iterations.";
return 0;
}