Next Smallest Palindrome!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| string Solution::solve(string s) { int r = s.length() / 2, l = r - (s.length() % 2 == 0); int pass = 0; while(l >= 0 and pass == 0) { if(s[l] == s[r]) l--,r++; else if(s[l] > s[r]) pass = 1; else pass = -1; } if(pass != 1) { r = s.length() / 2, l = r - (s.length() % 2 == 0); int carry = 1; while(l >= 0 and carry) { int now = s[l] - '0' + carry; carry = now / 10; now %= 10; s[l] = now + '0'; l--; } if(carry) s = "1" + s; } l = 0, r = s.size() - 1; while(l < r) { s[r] = s[l]; l++,r--; } return s; }
|