fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <regex>
  4. #include <vector>
  5. #include <algorithm>
  6.  
  7. using namespace std;
  8.  
  9. vector<long long> NearestPalindromeNumbers(long long n)
  10. {
  11. string s = to_string(n);
  12. if (regex_match(s, regex("^10+$"))) return {n - 1, n + 1};
  13.  
  14. int j = s.length() / 2;
  15. int i = s.length() - j;
  16. reverse_copy(&s[0], &s[j], &s[i]);
  17. long long x = stoll(s);
  18. if (x == n) return {x};
  19.  
  20. s.replace(0, i, to_string(stoll(s.substr(0, i)) + (x < n ? 1 : -1)));
  21. reverse_copy(&s[0], &s[j], &s[i]);
  22. long long y = stoll(s);
  23. long long d = abs(x - n) - abs(y - n);
  24. if (d < 0) return {x};
  25. if (d > 0) return {y};
  26. if (x < y) return {x, y}; else return {y, x};
  27. }
  28.  
  29. int main(void)
  30. {
  31. long long q[] = {0, 5, 10, 17, 100, 1000, 2024, 12345679042654321};
  32.  
  33. for (auto n : q) {
  34. auto v = NearestPalindromeNumbers(n);
  35. for (auto &x : v) cout << (&x == &v[0] ? "[" : ", ") << x;
  36. cout << "]" << endl;
  37. }
  38. return 0;
  39. }
Success #stdin #stdout 0.01s 5304KB
stdin
Standard input is empty
stdout
[0]
[5]
[9, 11]
[22]
[99, 101]
[999, 1001]
[2002]
[12345678987654321, 12345679097654321]