My code runs in 4ms. How can I make it faster ?


  • 0
    S
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
            ListNode l1r = l1;
            ListNode l2r = l2;
            ListNode head = null;
            ListNode ln = null;
            int carry = 0;
            int i=0;
             head = new ListNode((l1r.val+l2r.val+carry)%10);
             carry = (l1r.val+l2r.val+carry)/10;
             l1r = l1r.next;
             l2r = l2r.next;
             
             ln = head;
            while(l1r!=null && l2r!=null){
                if(head.next==null){
                    head.next = new ListNode((l1r.val+l2r.val+carry)%10);
                }
                head = head.next;
                int temp = l1r.val + l2r.val + carry;
                head.val = (temp)%10;
                carry = (temp)/10;
                l1r = l1r.next;
                l2r=l2r.next;
                //head.next = new ListNode(-1);
                
               // i++;
            }
          
            if(l1r==null && l2r!=null){
                
                    while(l2r!=null){
                        head.next = new ListNode((l2r.val+carry)%10);
                        head= head.next;
                        head.val = (l2r.val+carry)%10;
                        carry = (l2r.val+carry)/10;
                        l2r = l2r.next;
                        
                        
                    }
            }
                            
            if(l2r==null && l1r!=null)
            {
                while(l1r!=null){
                        head.next = new ListNode((l1r.val+carry)%10);
                        head= head.next;
                        head .val = (l1r.val+carry)%10;
                        carry = (l1r.val+carry)/10;
                        l1r = l1r.next;
                      
                    }
                
            }
           if(l1r==null && l2r == null){
              if(carry!=0){
                        head.next = new ListNode((carry)%10);
                        head = head.next;
                    }
            }
         
            
            
            return ln;
    }

Log in to reply
 

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