0

I am getting an error when converting a string to an int on line 8.

The integer parseInt method doesn't seem to be doing its job.

I have tried to use other methods to convert the string but nothing is working and its causing me to fail this coding challenge I'm doing. I have cut the rest of the code because the error in my logic is in these lines.

The error message reads



     java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
       at java.lang.Integer.parseInt(Integer.java:583)
       at java.lang.Integer.parseInt(Integer.java:615)
    at Solution.reverseNum(Solution.java:35)
        at Solution.main(Solution.java:8)


    public class Solution {
        public static void main(String args[] ) throws Exception {
            String sc = "1234567890123456";
            int noCases = 1;
            for(int i=0; i<noCases; i++){
                int rev = reverseNum(sc); 
            } // for each credit card number
        }

        public static int reverseNum(String inp){ // helper function
            int in =Integer.parseInt(inp); 
            int res  = 0;
            for(int i = in; i !=0; i/=10){
                res = res *10 + i%10;
            }
            return res;
        }
    }

Kevin M
  • 1
  • 2
  • Why are you converting your `String` into a number to reverse it in the first place? Why not just use [`StringBuilder#reverse()`](https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html#reverse--)? – azurefrog Sep 26 '19 at 15:59
  • Wow, thanks azurefrog never knew about that method until now! – Kevin M Sep 26 '19 at 16:17

1 Answers1

1

1234567890123456 is too big to be an int. Here, take a look at it with commas: 1,234,567,890,123,456. That's a quadrillion.

The biggest possible int is 2,147,483,647. Try a smaller number or Long.parseLong()

Malt
  • 28,965
  • 9
  • 65
  • 105