Reputation: 13
I'm trying to solve a question where your code is supposed to determine if a given number is a palindrome or not, and I don't understand why it isn't working.
(You can skip this and just read the code if you want) The idea was that I create a string with the value of the integer, and create a for loop using the length of said string that uses % 10 to reverse the integer and store it in a separate string. I would then compare the 2 strings to determine if the number is a palindrome or not
public static boolean isPalindrome(int x) {
String s = String.valueOf(x);
int count = s.length();
String palindrome = "";
for(int i = 0; i < count; i++){
palindrome += x % 10;
}
System.out.print(palindrome);
if(palindrome == s){
return true;
}
else{
return false;
}
}
The problem is that the code only returns false, and when I added a print statement to check what the reversed number (String palindrome) is, I got a different number.
For ex. I used 121 to test it and after the for loop the print statement outputted 111.
I'm not really looking for a solution, I just want to understand why it's behaving like this. Thanks in advance.
Upvotes: 0
Views: 85
Reputation: 552
for(int i = 0; i < count; i++){
palindrome += x % 10;
}
Since x
does not change in that loop (or indeed anywhere in the code), each execution yields the same thing, the least significant digit of x
.
Thus palindrome
has some number of copies of the same digit, and will almost never equal s
You need to divide x
by 10 each time around the loop.
Upvotes: 1