In LeetCode, I'm attempting to answer another question. I agree it's a simple question, but it keeps me on track. It's similar to trying to build muscle by lifting light weights at first.
Question - 2 :-
Given an integer x
, return true
if x
is a
palindrome
, and false
otherwise.
Example Inputs:
Example 1:
Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.
Example 2:
Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Solution:
First approach:
class Solution {
public boolean isPalindrome(int x) {
int originalNumber = x;
int reversedNumber = 0;
while(x > 0) {
int lastDigit = x % 10;
reversedNumber = (reversedNumber * 10)+ lastDigit;
x = x/10;
}
return (originalNumber == reversedNumber);
}
}
Here's the explanation for the above code
The variable
originalNumber
is initialized with the value ofx
, so that we can compare it with the reversed number later.The variable
reversedNumber
is initialized with 0, which will hold the reversed number of the inputx
.A while loop is used to reverse the input number. The loop will run until the input number
x
becomes 0.Inside the loop, the last digit of
x
is extracted by performingx % 10
and stored in thelastDigit
variable.The extracted digit is added to the
reversedNumber
by multiplying it with 10 and adding thelastDigit
. This reverses the digits of the number.The last digit of
x
is removed by dividing it with 10 (x/10
) in order to extract the next digit in the next iteration of the loop.Finally, the method returns a boolean value indicating whether the original number and the reversed number are equal. If they are equal, then the input number
x
is a palindrome; otherwise, it is not.
Second approach:
class Solution {
public boolean isPalindrome(int x) {
String number = String.valueOf(x);
String reversedNumber = new StringBuilder(number).reverse().toString();
return number.equals(reversedNumber);
}
}
If we know how to use inbuilt methods in Java, our lives will be much easier. Above is one among them
The code workflow is very simple:
The integer
x
is converted to a String using thevalueOf()
method of the String class and stored in a variable callednumber
.The
number
String is reversed using thereverse()
method of the StringBuilder class, which creates a new StringBuilder object with thenumber
String as its initial value, reverses it and converts it back to a String using thetoString()
method. The reversed string is stored in a variable calledreversedNumber
.The
equals()
method of the String class is used to comparenumber
andreversedNumber
, and the result of the comparison is returned as a boolean value.
Overall, the method checks if the input integer is equal to its reverse as a string. If it is, it returns true
; otherwise, it returns false
.