Thursday, September 14, 2023

 Check if a number is Palindrome



In the previous post, we have gone through the Java programs of checking if String is palindrome.
To check if a number is palindrome, we need to perform the following steps:

  1. Copy the input number to a new variable
  2. Use modulo (%) to get the last digit
  3. Add the last digit to the reversed number
  4. Remove the last digit from the new variable using / (division sign)

Here is the Java code:


public boolean isPalindrome(int input) {
int number = input;
int reverse = 0;

while (number != 0) {
int reminder = number % 10; // get the last digit
reverse = (reverse * 10) + reminder; // add the last digit to the reverse variable
number = number / 10; // remove the last digit
}

return reverse == input;
}


If you are wondering why do we need to multiply the reverse by 10, it's because if we just add the reminder that would be wrong. 

Example: Let's say the input value is 123. Now, in the first iteration we add the number 3 to the reverse variable. In the next iteration, the reminder is 2 and if we do reverse + reminder, the result would be 3 + 2 = 5. So that is not what we want. We need to get 32, so we need to multiply the reverse by 10. It should be like this - (3 * 10) + 2 = 30 + 2 = 32.


And that is how we can check if a number is palindrome or not.



No comments:

Post a Comment