Code & Func
2017-09-30

打卡,第7天

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

从示例来看,这里的digits应该是倒过来的,即2->4->3表示的是342

如果它不是倒过来的话,我们可能还需要用栈去将元素取出来。

虽然这是一道Medium的题目,但是难度其实很小,思路大概是:

将当期指针所指向的值相加得到一个数x,那么x%10就是这个位应该为的数,x/10就是进位,所以算法思路很简单:

1
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
2
3
int ans,add = 0;
4
ListNode ret(0); //头结点让单链表操作变简单
5
ListNode *p = &ret;
6
while(l1 != nullptr && l2 != nullptr){
7
ans = (l1->val + l2->val) + add; //记得加上进位
8
add = ans/10; //求出进位
9
p->next = new ListNode(ans%10);
10
p = p->next;
11
l1 = l1->next;
12
l2 = l2->next;
13
}
14
while(l1){
15
ans = l1->val + add;
15 collapsed lines
16
add = ans/10;
17
p->next = new ListNode(ans%10);
18
p = p->next;
19
l1 = l1->next;
20
}
21
while(l2){
22
ans = l2->val + add;
23
add = ans/10;
24
p->next = new ListNode(ans%10);
25
p = p->next;
26
l2 = l2->next;
27
}
28
if (add != 0) p->next = new ListNode(add);//记得出来进位不为0的情况
29
return ret.next;
30
}

dicuss中还有一个更精炼的写法:

1
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
2
ListNode ret(0);
3
ListNode *p = &ret;
4
int add = 0,sum;
5
while(l1 || l2 || add){
6
sum = (l1?l1->val:0) + (l2?l2->val:0) + add;
7
add = sum/10;
8
p->next = new ListNode(sum%10);
9
p = p->next;
10
l1 = (l1?l1->next:nullptr);
11
l2 = (l2?l2->next:nullptr);
12
}
13
return ret.next;
14
}
上一条动态