PTA 乙级 1079 延迟的回文数 (20 分)
作者:互联网
测试点3,4,5是对输入N是否为回文数的判断
测试点6存在大数运算,不能单纯进行整数的加减,需要进行一位一位的处理
C++
1 #include <iostream> 2 #include <string> 3 #include <algorithm> 4 5 using namespace std; 6 7 bool isPalindromeNumber(string &s) { //判断回文数的函数 8 for (int i = 0; i < s.size() / 2; ++i) { 9 if(s[i] != s[s.size() - 1 - i]) return 0; 10 } 11 return 1; 12 } 13 14 int main() { 15 string N, rN; 16 string sum; 17 cin >> N; 18 bool N_judge = isPalindromeNumber(N); 19 if (N_judge) { //测试点3,4,5,首先对N进行判断是否为回文数 20 cout << N << " is a palindromic number." << endl; 21 return 0; 22 } 23 for(int i = 0; i < 10; ++i) { 24 rN = N; 25 reverse(N.begin(), N.end()); 26 int carry_bit = 0; 27 for (int j = N.size() - 1; j >= 0; --j) { //测试点6会进行大数运算,所以不能普通的整数加减,需要进行进位加法处理 28 int tmp = (N[j] - '0') + (rN[j] - '0') + carry_bit; 29 carry_bit = 0; 30 if (tmp >= 10) { 31 carry_bit = 1; 32 tmp -= 10; 33 } 34 sum = to_string(tmp) + sum; 35 } 36 if(carry_bit) sum = to_string(carry_bit) + sum; //判断加到最后是否存在进位 37 bool judge = isPalindromeNumber(sum); 38 cout << rN << " + " << N << " = " << sum << endl; 39 if(judge) { 40 cout << sum << " is a palindromic number." << endl; 41 return 0; 42 } 43 N = sum; 44 sum.clear(); //记得对加和的字符串进行清除,方便下一轮判断重复利用 45 } 46 cout << "Not found in 10 iterations." << endl; 47 return 0; 48 }
标签:tmp,20,string,测试点,1079,sum,PTA,carry,bit 来源: https://www.cnblogs.com/SCP-514/p/15369700.html