Leetcode 2 Add Two Numbers 兩數相加

Add Two Numbers java

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.node

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8git

這題是說: 給出兩個鏈表, 每一個鏈表表明一個多位整數, 個位在前. 好比2->4->3表明着342. 求這兩個鏈表表明的整數之和(342+465=807), 一樣以倒序的鏈表表示.code

難度: Mediumit

這個題目就是模擬人手算加法的過程, 須要記錄進位. 每次把對應位置, 兩個節點(若是一個走到頭了, 就只算其中一個的值), 加上進位值, 做爲結果節點的值, 若是大於9, 須要把進位剝離出來.io

public class Solution {
    public class ListNode {
        int      val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int addUp = 0;
        ListNode ret = null;
        ListNode cur = null;
        while (l1 != null || l2 != null) {
            if (cur == null) {
                cur = ret = new ListNode(0);
            } else {
                cur.next = new ListNode(addUp);
                cur = cur.next;
            }
            cur.val += (l1 == null ? 0 : l1.val) + (l2 == null ? 0 : l2.val);
            addUp = cur.val / 10;
            cur.val = cur.val % 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (addUp > 0) {
            cur.next = new ListNode(addUp);
        }
        return ret;
    }

    public static void main(String[] args) {
        Solution s = new Solution();
        ListNode a = s.new ListNode(2);
        a.next = s.new ListNode(4);
        a.next.next = s.new ListNode(3);
        ListNode b = s.new ListNode(5);
        b.next = s.new ListNode(6);
        // b.next.next = s.new ListNode(4);
        ListNode c = s.addTwoNumbers(a, b);
        while (true) {
            System.out.println(c.val);
            if (c.next != null) {
                c = c.next;
            } else {
                break;
            }
        }
    }
}
相關文章
相關標籤/搜索