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 the 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.
CodePudding user response:
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.
CodePudding user response:
The problem is your for-loop. Every time the the for-loop iterates you have also to divide by 10 your x
public static boolean isPalindrome(int x) {
String numStr = String.valueOf(x);
StringBuilder palindrome = new StringBuilder();
for(; x>0; x /=10) {
palindrome.append(x % 10);
}
return palindrome.toString().equals(numStr);
}
In this for-loop is missing the initialisation because you don't need the index. In fact you can replace the for loop with a while loop:
while (x>0) {
palindrome.append(x % 10);
x /= 10;
}
Note: I have also simplify your return. You can use the method equals()
that return true
if the two strings are equal.
Note: When you want to append strings its a better practice use a StringBuilder
than use the =
operator.