Line 25: java.lang.NumberFormatException: For input string: "3999999999"


  • 0
    H

    Hi guys,

    I am not sure why this statement int num1 = Integer.parseInt(st.trim()); in my code gave the NumberFormat exception. I guess the integer returned from the Integer parse was just too big for int value. If that is the case, how do I resolve this? Also, kindly take alook and let me know if I have missed something in the code.

    public class Solution {
        public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        StringBuilder s1 = new StringBuilder();
        StringBuilder s2 =  new StringBuilder();
       
        while(l1!=null){
           s1.append(String.valueOf(l1.val));
           l1 = l1.next;
        }
        
         while(l2!=null){
         s2.append(String.valueOf(l2.val));
         l2=l2.next;
         }
         String st = s1.toString();
         String sd = s2.toString();
         int num1 = Integer.parseInt(st.trim());
         int num2=  Integer.parseInt(sd.trim());
         int sum = num1+num2;
         return storeDigits(sum);
    
        }
        
        public ListNode storeDigits(int num){
        int digit = num%10;
        ListNode head = new ListNode(digit);
        num = num/10;
        ListNode currentNode = head;
    	
        while(num!=0){
           digit = num%10;
           while(currentNode.next!=null){
        	   currentNode = currentNode.next;
           }
           currentNode.next = new ListNode(digit);
            num = num/10;
            
        }
        return head;
        }
    }
    
    

  • 0
    C
    This post is deleted!

  • 0
    G

    "3999999999" is too big to be stored in to an int type. So you should change your variable type to long.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.