53 ms Java Solution


  • 0
    M

    public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    ListNode result = new ListNode(0);
    ListNode temp = result;

        ListNode zeroNode = new ListNode(0);
        int sum = 0;
        while (true) {
            sum = l1.val + l2.val + temp.val;
            temp.val = sum % 10;
            
            if (l1.next == null && l2.next == null) {
                break;
            } else if (l1.next == null) {
                l1 = zeroNode;
                l2 = l2.next;
            } else if (l2.next == null) {
                l1 = l1.next;
                l2 = zeroNode;
            } else {
                l1 = l1.next;
                l2 = l2.next;
            }
            
            temp.next = new ListNode(sum / 10);
            temp = temp.next;
        }
        
        if (sum >= 10) {
            temp.next = new ListNode(1);
        }
        
        return result;
    }
    

    }


Log in to reply
 

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