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.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
普通解法
这道题重在思路,编程没有什么c++技巧。我的思路如下:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode*l3=new ListNode(0);
ListNode *head=l3;
int carry=0;
while(l1!=NULL and l2!=NULL){
if(l1->val+l2->val+carry<10){
l3->val=l1->val+l2->val+carry;
carry=0;
}
else {
l3->val=(l1->val+l2->val+carry)%10;
carry=(l1->val+l2->val+carry)/10;
}
l1=l1->next;
l2=l2->next;
if(carry!=0 or l1!=NULL or l2!=NULL){
l3->next=new ListNode(0);
l3=l3->next;
l3->val=carry;
}
}
while(l1){
if(l1->val+carry<10){
l3->val=l1->val+carry;
carry=0;
}
else {
l3->val=(l1->val+carry)%10;
carry=(l1->val+carry)/10;
}
l1=l1->next;
if(carry!=0 or l1!=NULL) {
l3->next = new ListNode(0);
l3 = l3->next;
l3->val=carry;
}
}
while(l2){
if(l2->val+carry<10){
l3->val=l2->val+carry;
carry=0;
}
else {
l3->val=(l2->val+carry)%10;
carry=(l2->val+carry)/10;
}
l2=l2->next;
if(carry!=0 or l2!=NULL) {
l3->next = new ListNode(0);
l3 = l3->next;
l3->val=carry;
}
}
return head;
}
我将本题,分为两种情况
- 两个列表长度相同时:依次计算,然后单独考虑进位情况
- 两个列表长度不同时:先用1方法计算,然后再用循环来遍历剩下的链表
while(l1){
if(l1->val+carry<10){
l3->val=l1->val+carry;
carry=0;
}
else {
l3->val=(l1->val+carry)%10;
carry=(l1->val+carry)/10;
}
l1=l1->next;
if(carry!=0 or l1!=NULL) {
l3->next = new ListNode(0);
l3 = l3->next;
l3->val=carry;
}
}
高级解法
高级解法,时间复杂度上并没有提高,但代码很精简,利用了递归解决问题:
public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
if (l1 == null || l2 == null) {
return l1 == null ? l2 : l1;
}
int value = l1.val + l2.val;
ListNode result = new ListNode(value % 10);
result.next = addTwoNumbers2(l1.next, l2.next);
if (value >= 10) {
result.next = addTwoNumbers2(new ListNode(value / 10), result.next);
}
return result;
}
这里不推荐用递归方法求解,因为牺牲的代价太大了