LeetCode Problems 003
Problems 002 - Add Two Numbers[两数相加]
1. 题目
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.
2. 解决方法
2.1 C++ 解法
(1)C++ 解法一
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *head=new ListNode(0);
ListNode *result=head;
int mask=makeSum(l1,l2,result);
ListNode *pre=l1?l1:l2;
while(pre)
{
int val=pre->val+mask;
mask=val/10;
ListNode *p=new ListNode(val%10);
result->next=p;
result=result->next;
pre=pre->next;
}
if(mask)
result->next=new ListNode(mask);
ListNode *ret=head->next;
return ret;
}
int makeSum(ListNode * &l1,ListNode * &l2, ListNode * &result)
{
int mask=0;
while(l1&&l2)
{
int val=l1->val+l2->val+mask;
mask=val/10;
ListNode *p=new ListNode(val%10);
result->next=p;
result=result->next;
l1=l1->next;
l2=l2->next;
}
return mask;
}
};