Skip to content
Advertisement

Why String index out of range?

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!

JavaScript

Advertisement

Answer

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

JavaScript

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

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement