/**
* 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 * head = new ListNode(-1);
ListNode * pt = head;
int carry = 0;
while(l1 != NULL || l2 != NULL) {
int sum = 0;
if(l1 != NULL && l2 != NULL) {
sum = l1->val + l2->val + carry;
l1 = l1->next;
l2 = l2->next;
} else
if(l1 != NULL && l2 == NULL) {
sum = l1->val + carry;
l1 = l1->next;
} else
if(l1 == NULL && l2 != NULL) {
sum = l2->val + carry;
l2 = l2->next;
}
carry = sum / 10;
pt->next = new ListNode(sum % 10);
pt = pt->next;
}
if(carry) pt->next = new ListNode(carry);
return head->next;
}
};
3/30/2014
Leetcode -- Add Two Numbers
Solution 03/30/2014
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment