Add Two Numbers
LeetCode #2
Description:
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
Idea:
用carry表示进位,要处理好到最后是否创建新node
的情况。
Method 1 更简洁
Code:
Method 1
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry=0;
ListNode dummy(-1);
ListNode *curr=&dummy;
while(l1!=NULL || l2!=NULL){
int sum=carry;
if(l1!=NULL){
sum += l1->val;
l1=l1->next;
}
if(l2!=NULL){
sum += l2->val;
l2=l2->next;
}
curr->next=new ListNode(sum%10);
curr=curr->next;
carry=sum/10;
}
if(carry){
curr->next = new ListNode(1);
}
return dummy.next;
}
};
Method 2
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if(l1==NULL || l2==NULL) return l1==NULL? l2 : l1;
ListNode dummy(-1);
ListNode *curr = &dummy;
int carry = 0;
int add_digit;
while(l1!=NULL && l2!=NULL){
add_digit = l1->val + l2->val + carry;
carry = add_digit/10;
curr->next = new ListNode(add_digit%10);
curr=curr->next;
l1=l1->next;
l2=l2->next;
}
ListNode *l_remain = l1==NULL? l2: l1;
while(l_remain!=NULL && carry!=0){
add_digit = l_remain->val + carry;
carry = add_digit/10;
curr->next = new ListNode(add_digit%10);
curr=curr->next;
l_remain = l_remain->next;
}
if(carry==0)
curr->next=l_remain;
else
curr->next=new ListNode(carry);
return dummy.next;
}
};