Two numbers together
Title Description
We are given two non-empty list is used to represent two non-negative integer. Where their respective bits are stored in reverse order of the way, and they each node can store only one digit. If we add up these two numbers, it will return a new list and to represent them. You can assume that in addition to the numbers 0, these two numbers will not begin with 0.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Cause: 342 + 465 = 807
Detailed explanations
Analog adder using carry variable to track the carry, and from the group consisting of the least significant bit header start bit added by the simulation.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
struct ListNode *result = NULL;
struct ListNode *l3 = NULL;
int carry = 0;
int val1, val2;
if (!l1 && !l2) {
return NULL;
}
while (l1 || l2 || carry) {
if (l1) {
val1 = l1->val;
l1 = l1->next;
} else {
val1 = 0;
}
if (l2) {
val2 = l2->val;
l2 = l2->next;
} else {
val2 = 0;
}
if (!l3) {
l3 = malloc(sizeof(struct ListNode));
assert(l3 != NULL);
result = l3;
} else {
l3->next = malloc(sizeof(struct ListNode));
assert(l3->next != NULL);
l3 = l3->next;
}
l3->val = (val1 + val2 + carry) % 10;
l3->next = NULL;
carry = (val1 + val2 + carry) / 10;
}
return result;
}
method | time complexity | Space complexity | result | time | RAM |
---|---|---|---|---|---|
method | time complexity | Space complexity | result | time | RAM |
Analog adder | O (max (l1.len, l2.len)) | O (max (l1.len, l2.len)) | by | 24ms | 8.9M |