Share my 420ms solution


  • 0
    T
    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode current = new ListNode(0);
        ListNode result = current;
        
        int carry = 0;
        int sum = 0;
        
        while(l1 != null || l2 != null || carry != 0){
            int val1;
            int val2;
            
            if(l1 == null){
                val1 = 0;
            }else{
                val1 = l1.val;
                l1 = l1.next;
            }
            
            if(l2 == null){
                val2 = 0;
            }else{
                val2 = l2.val;
                l2 = l2.next;
            }
            
            sum = val1 + val2 + carry;
            if(sum >= 10){
                sum -= 10;
                carry = 1;
            }else{
                carry = 0;
            }
            
            if(!(l1 == null && l2 == null && carry == 0)){
                current.next = new ListNode(0);
            }
            
            current.val = sum;
            current = current.next;
        }
        return result;
    }

  • 0
    T

    I also have a recursive version(480ms) which is a little bit slower than this one.


  • 0
    K

    This fails the test case
    int[] t1 = {9, 0, 0};
    int[] t2 = {9, 8};

    Output: [9, 8, 0]
    Expected: [9, 8]


Log in to reply
 

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