本题主要考察大数相加,有注意点:
1.使用reverse函数可以快速反转string
2.若是常规的大数相加,记得注意两数的长度来控制遍历条件。
1 #include<bits/stdc++.h> 2 using namespace std; 3 string n; 4 int k; 5 bool isPalindromicNumber(string x) { 6 string y = x; 7 reverse(y.begin(), y.end()); 8 if (x == y) { 9 return true; 10 } 11 return false; 12 } 13 string add(string x) { 14 string y = x; 15 reverse(y.begin(), y.end()); 16 string res; 17 bool isover = false; //进位符 18 for (int i = x.length() - 1; i >= 0; -- i) { 19 int a = x[i] - '0', b = y[i] - '0'; 20 int sum = a + b; 21 if (isover) { 22 sum += 1; 23 } 24 if (sum > 9) { 25 isover = true; 26 sum -= 10; 27 } else { 28 isover = false; 29 } 30 res.push_back('0' + sum); 31 } 32 if (isover) { //注意要判断最高位是否有进位 33 res.push_back('1'); 34 } 35 reverse(res.begin(), res.end()); 36 return res; 37 } 38 39 int main() { 40 cin >> n >> k; 41 for (int i = 0; i <= k; ++ i) { 42 if (isPalindromicNumber(n) || k == i) { 43 cout << n << endl; 44 cout << i << endl; 45 break; 46 } 47 n = add(n); 48 } 49 }
标签:isover,1024,string,Palindromic,int,res,sum,Number,reverse From: https://www.cnblogs.com/coderhrz/p/18559371