Week2:Add Two Numbers(Medium)
1. Question
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
2. Solution
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode *temp = new ListNode(0);
ListNode *p = temp;
int carry = 0;
int flag = false;
while(l1 || l2 || carry) {
if(flag) {
p->next = new ListNode(0);
p = p->next;
}
int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
carry = sum / 10;
p->val = sum % 10;
l1 = l1 ? l1->next : l1;
l2 = l2 ? l2->next : l2;
flag = true;
}
return temp;
}
};
思路:利用l1、l2和carry來判斷是否還需要對p->next進行賦值,其中carry爲l1和l2當前位的進位,同時利用flag來避免最後多出一位。時間複雜度爲O(n)。