I'm trying to check if an integer is a palindrome in Java, but I'm stuck with cases where the input is a number like 1000021. I can get most cases right, but this specific one fails. I don't want a full solution; just a hint that could help me figure it out! Here's my code:
```java
class Solution {
public boolean isPalindrome(int x) {
String number = Integer.toString(x);
int length = (int) (Math.log10(x));
if (number.contains("-") || number.charAt(0) == '0') {
return false;
}
if (length == 0 || x == 0) {
return true;
}
for (int i = length; i >= 0; i--) {
for (int j = 0; j <= length - 1; j++) {
if (number.charAt(i) == number.charAt(j)) {
return true;
} else {
return false;
}
}
}
return false;
}
}
```
Can anyone provide a hint? I'm a bit confused about my loops and I just want to get this sorted!
2 Answers
A good hint would be to avoid nested loops. Since you're trying to compare characters from both ends of the string, you should consider moving both pointers in tandem. When one goes down, the other should go up. This way, you can check if the characters at those positions match without needing to compare every possible combination, which is what's happening in your code now.
It looks like your loops are the main problem here. The `log10(x)` method you’re using doesn't give the last index correctly for strings. Plus, returning true or false inside your nested loops means you will exit after the first check, which isn't right. You really only need a single loop to tackle this problem.

Thank you! Ill look into it!