标签:
/** * 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; } };
# 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
/** * 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