Thursday, February 12, 2015

Reverse Number and Check Number is Palindrome

I have explained previously about finding a Armstrong number. There we used modulus and division operators.
Same way we can reverse a given number, and one step ahead can check whether it is Palindrome.

what is Palindrome number ?
If any number equals its reverse number, we call them palindrome number.

So checking Palindrome we need to reverse the number.

So first look at reversing number.

--------------------------------------------------------------------------------
 public static int reverseNumber(int number){
        int reverseNumber = 0;
        int remainder = 0;
        do{
            remainder = number%10;
            reverseNumber = reverseNumber*10 + remainder;
            number = number/10;
         
        }while(number > 0);
     
        return reverseNumber;
    }

-----------------------------------------------------------------------
We use modulus to get the last digit of the number and rest of the numbers exclusive of last digit by division.

To check the palindrome ,  we can use this functionality.
Note: I have done using do while loop ,but this can be done using while loop as we have used in Armstrong number scenario.
So benefit i will use Palindrome number check with while loop.


------------------------------------------------------------------------------

public static boolean isPalindrome(int number) {
int palindromeNumber = number; // copied number into variable
int reverseNumber = 0;

while (palindromeNumber != 0) {
int remainder = palindromeNumber % 10;
reverseNumber = reverseNumber * 10 + remainder;
palindromeNumber = palindromeNumber / 10;
}

// original number equals reverse number , then it's Palindrome.
if (number == reverseNumber) {
return true;
}
return false;
}

-----------------------------------------------------------------------------------



No comments:

Post a Comment