Palindrome Number
How I solved Palindrome Number Problem.
A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam, racecar. We are doing this with numbers instead.
Input: 121
Output: trueInput: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
First i check for any negatives. Negatives can not be a palindrome number.
if(x < 0){
return false;
}
Then i came up with a plan to turn the number into a string then into an array so i can iterate over the number.
String number = Integer.toString(x);
int[] newNum = new int[number.length()];
Then i added all the integers into the array i created.
for(int i = 0; i < newNum.length; i++){
newNum[i] = number.charAt(i) - '0';
}
I love the two pointer technique , when comparing arrays. I created the two pointers earlier.
int start = 0;
int end = newNum.length;while(start < end){
if(newNum[start] != newNum[end-1] ){
return false;
}
start++;
end--;
}
return true;
There you have it. My version of solving the palindrome number .
class Solution {
public boolean isPalindrome(int x) {
if(x < 0){
return false;
}
String number = Integer.toString(x);
int[] newNum = new int[number.length()];
int start = 0;
int end = newNum.length;
for(int i = 0; i < newNum.length; i++){
newNum[i] = number.charAt(i) - '0';
}
while(start < end){
if(newNum[start] != newNum[end-1] ){
return false;
}
start++;
end--;
}
return true;
}
}