Leetcode 2. Add Two Numbers (Medium) (cpp)
Tag: Linked List, Math
Difficulty: Medium
/*
2. Add Two Numbers (Medium)
You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
*/
/*
* 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) {
int carry = 0;
ListNode *dummy = new ListNode(-1), *p = dummy;
for (ListNode *pa = l1, *pb = l2; pa || pb; p = p -> next) {
int ai = pa != NULL ? pa -> val : 0;
int bi = pb != NULL ? pb -> val : 0;
carry = ai + bi + carry;
p -> next = new ListNode(carry % 10);
carry /= 10;
pa = pa != NULL ? pa -> next : NULL;
pb = pb != NULL ? pb -> next : NULL;
}
if (carry) {
p -> next = new ListNode(carry);
}
return dummy -> next;
}
};