JunyiCode
4/23/2020 - 1:41 AM

2. Add Two Numbers

处理一长一短的问题

/*
note: 处理一长一短的问题
*/

class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode cur;
        cur = head;
        int carry = 0;
        
        while(l1 != null || l2 != null) {
            if(l1 != null) {
                carry += l1.val;
                l1 = l1.next;
            }
            if(l2 != null) {
                carry += l2.val;
                l2 = l2.next;
            }
            
            ListNode newNode = new ListNode(carry % 10);
            cur.next = newNode;
            cur = cur.next;
            carry /= 10;
        }
        
        if(carry != 0) {
            ListNode newNode = new ListNode(carry);
            cur.next = newNode;
        }
        
        return head.next;
    }
}