fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <algorithm>
  5.  
  6. long long *NearestPalindromeNumbers(long long n)
  7. {
  8. char s[32];
  9. static long long x[3];
  10.  
  11. int k = sprintf(s, "%lld", n);
  12. int j = k / 2;
  13. int i = k - j;
  14. strncpy(s + i, s, j)[j] = 0;
  15. std::reverse(s + i, s + k);
  16. x[0] = atoll(s);
  17. if (x[0] == n) return x[1] = -1, x;
  18.  
  19. s[i] = 0;
  20. k = sprintf(s, "%lld", atoll(s) + (x[0] < n ? 1 : -1));
  21. if (strcmp(s, "0") == 0) strcpy(s, "9"), j--;
  22. if (k < i) strcat(s, "9"), j--;
  23. strncpy(s + i, s, j)[j] = 0;
  24. std::reverse(s + i, s + i + j);
  25. x[1] = atoll(s);
  26.  
  27. long long d = abs(x[0] - n) - abs(x[1] - n);
  28. if (d < 0) return x[1] = -1, x;
  29. if (d > 0) return x[2] = -1, x + 1;
  30. return x[0] < x[1] ? x : (x[2] = x[0], x + 1);
  31. }
  32.  
  33. int main(void)
  34. {
  35. long long q[] = {0, 5, 10, 17, 100, 1000, 2024, 12345679042654321};
  36.  
  37. for (int i = 0; i < sizeof(q) / sizeof(*q); i++) {
  38. long long *x = NearestPalindromeNumbers(q[i]);
  39. for (int j = 0; j < 2; j++) if (x[j] >= 0) printf("%s%lld", j ? ", " : "[", x[j]);
  40. printf("]\n");
  41. }
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0s 5296KB
stdin
Standard input is empty
stdout
[0]
[5]
[9, 11]
[22]
[99, 101]
[999, 1001]
[2002]
[12345678987654321, 12345679097654321]