题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1024
注意一点,必须要用字符串,long long 也会溢出!
1 #include<iostream> 2 #include<vector> 3 #include<algorithm> 4 #include<string> 5 using namespace std; 6 7 bool palindromic(string n) 8 { 9 string n1(n); 10 reverse(n.begin(), n.end()); 11 if(n1 == n) 12 return true; 13 else 14 return false; 15 } 16 17 string process(string n) 18 { 19 string n1(n); 20 reverse(n.begin(), n.end()); 21 int carry(0); 22 string outcome; 23 for(int i=n1.size()-1; i>=0; --i) 24 { 25 int k=(n[i]-'0')+(n1[i]-'0')+carry; 26 carry=0; 27 if(k >= 10) 28 {carry = 1; k-=10;} 29 outcome.push_back((char)(k+'0')); 30 } 31 if(carry == 1) 32 outcome.push_back('1'); 33 reverse(outcome.begin(), outcome.end()); 34 return outcome; 35 } 36 37 int main() 38 { 39 string n; 40 int k; 41 while(cin>>n>>k) 42 { 43 int m(0); 44 while(m <= k) 45 if(palindromic(n)) 46 { 47 cout<<n<<endl<<m<<endl; 48 break; 49 } 50 else if(m == k) 51 { 52 cout<<n<<endl<<m<<endl; 53 break; 54 } 55 else 56 { 57 n=process(n); 58 ++m; 59 } 60 } 61 return 0; 62 }