fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static boolean isPalindrome(int x) {
  11. if (x == 0) return true;
  12. if (x < 0) return false;
  13.  
  14. int digitsCount = (int) Math.log10(x);
  15. return isPalindromeHelper(x, 0, digitsCount);
  16. }
  17.  
  18. private static boolean isPalindromeHelper(int x, int leftIndex, int rightIndex) {
  19. int leftDigit = getDigit(x, leftIndex),
  20. rightDigit = getDigit(x, rightIndex);
  21.  
  22. if (leftIndex == rightIndex) {
  23. return true;
  24. }
  25. else if (leftDigit != rightDigit) {
  26. System.out.println("leftDigit="+leftDigit + ", rightDigit=" + rightDigit);
  27. return false;
  28. } else {
  29. return isPalindromeHelper(x, leftIndex + 1, rightIndex - 1);
  30. }
  31. }
  32.  
  33. private static int getDigit(int x, int idx) {
  34. int digitsCount = (int) Math.log10(x);
  35. int divisor = ((int) Math.pow(10, digitsCount - idx));
  36. if (divisor == 0) return x % 10;
  37. System.out.println("divisor=" + divisor+",(x/divisor) %10=" + (x/divisor)%10);
  38. return (x / divisor) % 10;
  39. }
  40. public static void main (String[] args) throws java.lang.Exception
  41. {
  42. System.out.println(Ideone.isPalindrome(12321));
  43. }
  44. }
Success #stdin #stdout 0.19s 57548KB
stdin
Standard input is empty
stdout
divisor=10000,(x/divisor) %10=1
divisor=1,(x/divisor) %10=1
divisor=1000,(x/divisor) %10=2
divisor=10,(x/divisor) %10=2
divisor=100,(x/divisor) %10=3
divisor=100,(x/divisor) %10=3
true