天天看點

LeetCode 2. Add Two Numbers 解題報告

題意:

有兩個連結清單,它們表示逆序的兩個非負數。例 (2 -> 4 -> 3)表示342,求兩個數字的和,并用同樣的方式逆序輸出。如342+465 = 807,你需要把結果表達為(7 ->0 ->8)。

思路:

模拟一下加法的運算過程,從個位開始加,進位儲存下來,十位運算的時候把個位的進位加上,依次類推。

C++ Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode preHead(0), *p = &preHead;
        int extra = 0;
        while (l1 || l2 || extra) {
            int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra;
            extra = sum / 10;
            p->next = new ListNode(sum % 10);
            p = p->next;
            l1 = l1 ? l1->next : l1;
            l2 = l2 ? l2->next : l2;
        }
        return preHead.next;
    }
};
           

Python Code

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        p = preHead = ListNode(0)
        extra = 0
        while l1 or l2 or extra:
            extra, val = divmod((l1 and l1.val or 0) + (l2 and l2.val or 0) + extra, 10)
            p.next = ListNode(val)
            p = p.next
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next
        return preHead.next
           

JS Code

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
var addTwoNumbers = function(l1, l2) {
    var preHead = new ListNode(0)
    var p = preHead
    var extra = 0
    while(l1 !== null || l2 !== null || extra !== 0) {
        var sum = (l1 && l1.val || 0) + (l2 && l2.val || 0) + extra
        extra = (sum > 9) ? 1 : 0
        p.next = new ListNode(sum % 10)
        p = p.next
        l1 = l1 && l1.next || null
        l2 = l2 && l2.next || null
    }
    return preHead.next
};