Sunday, December 13, 2020

How to check a given number is a palindrome in Java ?

This is another online coding challenge I came across recently to which I found a simple solution with the use of String and StringBuffer in java. 

Let me explain the challenge here,

  • A given number is a palindrome when reversed is equal to the original number (e.g : 121, 45654,1001)
  • If the given number is a palindrome, then return true else return false
In my solution I basically convert the integer number to a string in order to reverse the number, Unfortunately java doesn't have a reverse method in String class (it's java 11 that I'm working with). However, StringBuilder has a reverse method to which a String needs to be parsed. So, here's what I'm doing.

get the Integer number --> convert to String --> convert to StringBuilder --> reverse the string --> convert back to String --> convert the string back to number --> store it in a new int variable --> compare with the original number --> return true if matches or return false unless otherwise

why do I use Math.abs() ?

This is simply to handle any negative numbers. for an instance, -232 is a palindrome but if we straight away convert it to string this will reverse the string as 232- which ends up with an invalid integer. To handle this, I have considered the absolute value by using Math.abs() function to only get the absolute value of the given number.

find my solution as below

public class NumberPalindrome {
public static boolean isPalindrome(int number){
boolean result = false;
number = Math.abs(number);
int reversedNumber = Integer.parseInt(new StringBuilder(String.valueOf(number)).reverse().toString());

if(number == reversedNumber){
result = true;
}
return result;
}
}

No comments:

Post a Comment