Struggling to Solve a Palindrome Problem in Code

0
7
Asked By jumpyFrog99 On

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

Answered By programmerPal On

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.

jumpyFrog99 -

Thank you! Ill look into it!

Answered By codeWizard92 On

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.