(LeetCode) 2. Add Two Numbers

文章目录

  1. 1. Original URL: 2. Add Two Numbers
  2. 2. My solutions:
    1. 2.1. With C++:
    2. 2.2. With Python:

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

Difficulty: Medium
Tags: Linked List, Math

Original URL: 2. Add Two Numbers

My solutions:

With C++:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* 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(0);
ListNode* out = head;
int v1 , v2 , vout , carry = 0;
while( l1 || l2 )
{ if(l1)
{ v1 = l1 -> val;
l1 = l1 -> next;}
else{ v1 = 0;}
if(l2)
{ v2 = l2 -> val;
l2 = l2 -> next;}
else{ v2 = 0;}
vout = v1 + v2 + carry;
if( vout > 9 )
{ carry = 1;
vout = vout % 10;}
else
{ carry = 0;}
head -> next = new ListNode(vout);
head = head -> next;
}
if( carry )
{head -> next = new ListNode(carry);}
return out -> next;
}
};

With Python:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""

head = out = ListNode(0)
array = 0
while(l1 or l2):
if(l1 and l2):
head.val = l1.val + l2.val + array
l1 = l1.next
l2 = l2.next
elif(l1):
head.val = l1.val + array
l1 = l1.next
else:
head.val = l2.val + array
l2 = l2.next
array = 0
if(head.val > 9):
head.val = head.val % 10
array = 1
if(l1 or l2):
head.next = ListNode(0)
head = head.next
elif(array):
head.next = ListNode(array)
head = head.next
return out

See my 30+ solutions of LeetCode on GitHub