
Problem Statement
This problem is from Leetcode – Palindrome Number. The problem statement is as below:
Given an integer x, return true if x is a palindrome, and false otherwise;
SOLUTION
In this question we are given an integer. We need to check if its a palindrome or not.
Approach
- First we need to extract the individual digits out of the input integer and store in an ArrayList.
- While input > 0 compute the modulus and store in the list. Further divide input by 10.
- Covert the ArrayList into an integer array. This contains the individual digits of the given input.
- Now in a for loop check if the first and last digits are the same. Break at the middle index.
- Time complexity of this approach is O(n).
Lets see the code below:
Palindrome.javapublic class PalindromeNumber { public static void main(String[] args) { PalindromeNumber pn = new PalindromeNumber(); boolean isPalin = pn.isPalindrome(12321); System.out.println("Panlindrome: " + isPalin); } public boolean isPalindrome(int x) { int num = x; boolean isPalin = true; // if the given input is negative then return false if(x < 0) { isPalin = false; } List<Integer> numList = new ArrayList<>(); /* using this while loop extract the digits from the input and push * into an ArrayList */ while (num > 0) { System.out.println ( num % 10); numList.add( num % 10); num = num / 10; } // end while // convert the ArrayList into an array Integer[] numArray = numList.toArray(new Integer[numList.size()]); int len = numArray.length-1; /* compare the first digit with the last digit. * Break out of the loop at middle index */ for(int i=0; i<numArray.length; i++) { if(i == (len-i)) { break; } else if(numArray[i] != numArray[len-i]) { isPalin = false; } } // end for return isPalin; } // end function } // end class
This code returns the output as below:
Panlindrome: true