fork download
  1. class NextPallindrome {
  2.  
  3. public static void main(String[] argc){
  4. int num= 8646;
  5. System.out.println(nextPanlindrome(num));
  6. }
  7.  
  8. /**
  9. * Get next pallindrome
  10. * @param num
  11. * @return
  12. */
  13. public static int nextPanlindrome(int num) {
  14.  
  15. if(isPalindrome(num))
  16. num++;
  17.  
  18. String temp = num + "";
  19. int end=temp.length() -1;
  20. int base=1;
  21.  
  22. for(int start = 0; start < end; start++, end--)
  23. {
  24.  
  25. // Gives the right digit
  26. int right = Integer.parseInt(temp.charAt(end)+"") * base;
  27.  
  28. // Gives the left digit
  29. int left = Integer.parseInt(temp.charAt(start)+"") * base;
  30.  
  31. // add differnce to the number
  32. num = num + left - right ; //------(1)
  33.  
  34. base *=10;
  35.  
  36. if(right > left)
  37. {
  38. num += base; // for incresing the value of number which got decreased at (1)
  39.  
  40. // previous step indroduces asymmetry if its a even number.
  41. if(start == end - 1) // For even numbers eg. case 8468 (adjacent digits)
  42. num += base/10;
  43. }
  44. temp = num + "";
  45. }
  46.  
  47. return num;
  48. }
  49.  
  50.  
  51. public static boolean isPalindrome(int num) {
  52. int reverse = 0, temp=num;
  53.  
  54. while( temp != 0 ) {
  55. reverse = reverse * 10;
  56. reverse = reverse + temp%10;
  57. temp = temp/10;
  58. }
  59. return (num == reverse ? true: false);
  60. }
  61. }
  62.  
Success #stdin #stdout 0.06s 380224KB
stdin
Standard input is empty
stdout
8668