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
};

 

你可能感兴趣的:(LeetCode 2. Add Two Numbers 解题报告)