[LeetCode 002] Add Two Numbers

Add Two Numbers

  • 使用carry记录进位情况,初始化为0
    • 如果l1节点存在,累加到carry中。
    • 如果l2节点存在,累加到carry中。
    • 新节点值carry % 10
    • 下一个节点进位carry
  • 最后carry1,新建一个值为1的节点

Implementation

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int carry = 0;
        ListNode anchor = new ListNode(0);
        ListNode head = anchor;
        while (l1 != null || l2 != null) {
            if (l1 != null) {
                carry += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                carry += l2.val;
                l2 = l2.next;
            }
            head.next = new ListNode(carry % 10);
            carry /= 10;
            head = head.next;
        }
        if (carry == 1)
            head.next = new ListNode(1);
        return anchor.next;
    }
}

你可能感兴趣的:([LeetCode 002] Add Two Numbers)