Skip to content

Commit 520ae9c

Browse files
author
Mauricio Klein
committed
Add solution for challenge #16
1 parent 812a72d commit 520ae9c

File tree

6 files changed

+61
-0
lines changed

6 files changed

+61
-0
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -48,3 +48,6 @@ build-iPhoneSimulator/
4848

4949
# unless supporting rvm < 1.11.0 or doing something fancy, ignore this:
5050
.rvmrc
51+
52+
# Python
53+
**/*.pyc

challenge-16/Makefile

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
test:
2+
python test_*.py
3+
4+
.PHONY: test

challenge-16/README.md

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# Add two numbers as a linked list
2+
3+
This problem was asked by Microsoft.
4+
5+
## Description
6+
7+
You are given two 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.
8+
9+
## Example
10+
11+
```
12+
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
13+
Output: 7 -> 0 -> 8
14+
Explanation: 342 + 465 = 807.
15+
```

challenge-16/__init__.py

Whitespace-only changes.

challenge-16/solver.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution:
2+
def addTwoNumbers(self, l1, l2):
3+
minSize = min(len(l1), len(l2))
4+
out = []
5+
carry = 0
6+
7+
for i in range(minSize):
8+
sum = l1[i] + l2[i] + carry
9+
10+
if sum > 9:
11+
out.append(sum-10)
12+
carry = 1
13+
else:
14+
out.append(sum)
15+
carry = 0
16+
17+
if len(l1) > minSize:
18+
for i in range(minSize, len(l1)):
19+
out.append(l1[i])
20+
21+
if len(l2) > minSize:
22+
for i in range(minSize, len(l2)):
23+
out.append(l2[i])
24+
25+
return out

challenge-16/test_solver.py

+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import unittest
2+
from solver import Solution
3+
4+
class TestSolver(unittest.TestCase):
5+
def test_solver(self):
6+
self.assertEqual(Solution().addTwoNumbers([2,4,3 ], [5,6,4 ]), [7,0,8 ])
7+
self.assertEqual(Solution().addTwoNumbers([2,4,3,1], [5,6,4 ]), [7,0,8,1])
8+
self.assertEqual(Solution().addTwoNumbers([2,4,3 ], [5,6,4,1]), [7,0,8,1])
9+
self.assertEqual(Solution().addTwoNumbers([1,2,3 ], [ ]), [1,2,3 ])
10+
self.assertEqual(Solution().addTwoNumbers([ ], [1,2,3 ]), [1,2,3 ])
11+
self.assertEqual(Solution().addTwoNumbers([ ], [ ]), [ ])
12+
13+
if __name__ == "__main__":
14+
unittest.main()

0 commit comments

Comments
 (0)