码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 2. Add Two Numbers 解题报告

时间:2016-01-06 20:08:33      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

题意:

有两个链表,它们表示逆序的两个非负数。例 (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 解题报告

标签:

原文地址:http://www.cnblogs.com/cxiaojia/p/5106676.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!