题目链接
分析:简单字符串反转,再加上加法计算,一开始用long long有两个测试点没过TAT。。估计是范围爆了10^10迭代相加100次,据大神说是10^40数量级,因此改用字符串进行加法操作。
补充:2018.8.11更新,博主再次倒在了数据范围上(可恶呀),后来测出了数据超出long long,改用字符串过。
更新代码:
#include<cstdio>
#include<algorithm>
#include<iostream>
using namespace std;
string convert(string num1){
int len = num1.length(), c = 0;
string num2 = num1, res = "";
reverse(num2.begin(), num2.end());
for(int i = 0; i<len; i++){
int tem = num1[i]+num2[i]-'0'-'0'+c;
c = tem/10;
res += tem%10+'0';
}
if(c) res += c+'0';
reverse(res.begin(), res.end());
return res;
}
int isPalindromic(string num){
int len = num.length();
for(int i = 0; i<len/2; i++)
if(num[i] != num[len-i-1]) return 0;
return 1;
}
int main(){
//freopen("aa.txt", "r", stdin);
string num;
int i, k;
cin >> num >> k;
for(i = 0; i<k; i++){
if(isPalindromic(num)) break;
num = convert(num);
}
cout << num << "\n" << i ;
return 0;
}
代码:
#include<bits/stdc++.h>
using namespace std;
bool isP(string tem){
for(int i = 0; i<tem.length()/2; i++){
if(tem[i] != tem[tem.length()-1-i]) return false;
}
return true;
}
string add(string a, string b){
string res="";
int c = 0,i=0;
for(i = 0; i<a.length(); i++){
int tem = a[i]+b[i]-'0'-'0'+c;
c = tem/10;
res += tem-c*10+'0';
}
if(c != 0) res+=c+'0';
reverse(res.begin(), res.end());
return res;
}
int main(){
long long k,cnt=0;
string a,b,res;
cin>>res>>k;
while(cnt < k && !isP(res)){
a = res;
b = a;
reverse(b.begin(), b.end());
res = add(a, b);
cnt++;
}
cout<<res<<"\n";
cout<<cnt<<"\n";
return 0;
}