Tuesday, July 11, 2017

Palindromic Number


public class PalindromeNumber {
  
    /*
        Problem: Check if the given number is palindromic. Ex. 1001 is palindromic but 17 is not
        Solution: You can find out number of digits in the of the decimal number by calculating
        Math.log10(x).
        Then you can use this information to calculate most significant and least significant digits
        and check if they are equal if not return false

        MSD of decimal = x / (Math.pow(10, Math.log10(x))
        LSD of decmial = x &10
     */
    public boolean isPalindromeNumber(int x){
        if(x <0)
            return false;
        int numberOfDigits = (int)(Math.floor(Math.log10(x)))+1;
        int msdMask =(int) Math.pow(10, numberOfDigits-1);
        for(int i = 0; i < numberOfDigits/2 ;i++){
            if( x / msdMask != x%10)
                return false;
            x = x %msdMask;
            x =  x/10;
            msdMask = msdMask /100;
        }
        return true;
    }
}

No comments:

Post a Comment