-1

below is my code for Leetcode 9 Palindrome Number. It shows "String index out of range error" for line 8 when the testcase is 121. Can anyone tell me why this happened? Thanks!

class Solution {
    public boolean isPalindrome(int x) {
        String s = String.valueOf(x);
        int i = 0;
        int j = s.length()-1;
        
        while(i < j){
            if(s.charAt(i) != s.charAt(j)){  <------ line 8
                return false;
            }else{
                s = s.substring(i+1,j);
            }
        }return true;
    }
}
Ken White
  • 123,280
  • 14
  • 225
  • 444
Binky
  • 27
  • 5
  • 1
    What does stepping through the code in the debugger tell you about what's happening? If you don't know how to use one, now is the perfect time to learn. There is no better tool available to a coder than the debugger, and it's never too early to start learning how to use it. – Ken White Nov 14 '21 at 15:30
  • 1
    Because of s = s.substring(i+1, j); You're shortening the string but not changing j – inordirection Nov 14 '21 at 15:33
  • @ Ken White Thanks for your reply! Can you please kindly suggest a tool for debugging as I am really new in this area. – Binky Nov 14 '21 at 15:33
  • @ Connor Robetorye Thanks!!! – Binky Nov 14 '21 at 15:34
  • The debugger that comes with every C and C++ compiler works fine. Java environments also include one. You've not indicated specifically which one you're using (or even included a tag for the language in which you're coding), so it's pretty difficult to be more specific. – Ken White Nov 14 '21 at 15:34
  • I am using java and I now just wring code on LeetCode website without the debugging feature as I haven't bought the membership. – Binky Nov 14 '21 at 15:36
  • Then start with [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – Ken White Nov 14 '21 at 15:37
  • @ Ken White Thanks! – Binky Nov 14 '21 at 15:39

1 Answers1

1

In the while loop, j remains constant whereas your "s" is reducing 1 char each loop. Example:

s = "theString";
i =0;j = 8;
loop 1: s = "theString";
loop 2: s = "heString";

as you see, s.subString(0, 8) will return the above exception because "s" is only 7 characters.

Minh Kieu
  • 475
  • 3
  • 9