Skip to content

Latest commit

 

History

History
48 lines (41 loc) · 1.35 KB

File metadata and controls

48 lines (41 loc) · 1.35 KB

2.Add Two Numbers

Leetcode link

解题思路

题目告诉我们每一个节点范围在 0 到 9 之间,并且贴心的帮我们倒序了(个位数在链表头,依次是十位,百位,千位。。。),那我们只需要另外创建一个链表,通过一次遍历加总之后返回链表头就可以了。这其中需要注意的就是加法会有进位,所以可以用一个 int 来存储进位值。

C++

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* result = new ListNode(0);
        ListNode* cur = result;
        int carry = 0;
        while (l1 || l2 || carry) {
         int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
         carry = sum / 10;
         cur->next = new ListNode(sum % 10);
         cur = cur->next;
         l1 = l1 ? l1->next : l1;
         l2 = l2 ? l2->next : l2;
        }
        return result->next;
    }
};

Javascript

var addTwoNumbers = function (l1, l2) {
	const result = new ListNode(0);
	let cur = result;
	let carry = 0;
	while (l1 || l2 || carry) {
		let sum = (l1 ? l1.val : 0) + (l2 ? l2.val : 0) + carry;
		carry = Math.floor(sum / 10);
		cur.next = new ListNode(sum % 10);
		cur = cur.next;
		l1 = l1 ? l1.next : l1;
		l2 = l2 ? l2.next : l2;
	}
	return result.next;
};