LeetCode - 2. Add Two Numbers

Posted 朝研行歌

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode - 2. Add Two Numbers相关的知识,希望对你有一定的参考价值。

Discription

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Solution

关键是处理好两个表的长度,以及进位问题,尤其是99+1=100这样特殊情况(和的长度比两个表的长度都大)的进位处理。

python

 1 class Solution(object):
 2     def addTwoNumbers(self, l1, l2):
 3         """
 4         :type l1: ListNode
 5         :type l2: ListNode
 6         :rtype: ListNode
 7         """
 8         testL1 = l1
 9         testL2 = l2
10         carry = 0
11         root = current = ListNode(0)
12 
13         while testL1 or testL2 or carry:
14             val1 = 0
15             val2 = 0
16             if testL1:
17                 val1 = testL1.val
18                 testL1 = testL1.next
19 
20             if testL2:
21                 val2 = testL2.val
22                 testL2 = testL2.next
23 
24             carry, mod_val = divmod(val1 + val2 + carry, 10)
25             current.next = ListNode(mod_val)
26             current = current.next
27 
28         return root.next

cpp

 1 class Solution {
 2 public:
 3     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
 4         ListNode header(0);
 5         ListNode *p = &header;
 6         int carry = 0;
 7         int sum = 0;
 8         int mod = 0;
 9         while (l1 || l2 || carry)
10         {
11             int val1 = 0;
12             int val2 = 0;
13             if (l1)
14             {
15                 val1 = l1->val;
16                 l1 = l1->next;
17             }
18             if (l2)
19             {
20                 val2 = l2->val;
21                 l2 = l2->next;
22             }
23             sum = val1 + val2 + carry;
24             carry = sum / 10;
25             mod = sum % 10;
26             p->next = new ListNode(mod);
27             p = p->next;
28         }
29 
30         return header.next;
31     }
32 };

 

Reference


以上是关于LeetCode - 2. Add Two Numbers的主要内容,如果未能解决你的问题,请参考以下文章

2. 两个数相加 [leetcode 2: Add Two Numbers]

2. 两个数相加 [leetcode 2: Add Two Numbers]

LeetCode - 2 - Add Two Numbers

[leetcode][2] Add Two Numbers

[LeetCode]2. Add Two Numbers

LeetCode - 2. Add Two Numbers