Skip to content

Commit 7ce6bb8

Browse files
committed
Create additive-number.py
1 parent f447739 commit 7ce6bb8

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Python/additive-number.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Time: O(n^3)
2+
# Space: O(n)
3+
#
4+
# Additive number is a positive integer whose digits can form additive sequence.
5+
#
6+
# A valid additive sequence should contain at least three numbers.
7+
# Except for the first two numbers, each subsequent number in the sequence
8+
# must be the sum of the preceding two.
9+
#
10+
# For example:
11+
# "112358" is an additive number because the digits can form an additive sequence:
12+
# 1, 1, 2, 3, 5, 8.
13+
#
14+
# 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, 3 + 5 = 8
15+
# "199100199" is also an additive number, the additive sequence is:
16+
# 1, 99, 100, 199.
17+
#
18+
# 1 + 99 = 100, 99 + 100 = 199
19+
# Note: Numbers in the additive sequence cannot have leading zeros,
20+
# so sequence 1, 2, 03 or 1, 02, 3 is invalid.
21+
#
22+
# Given a string represents an integer, write a function to determine
23+
# if it's an additive number.
24+
#
25+
# Follow up:
26+
# How would you handle overflow for very large input integers?
27+
#
28+
29+
class Solution(object):
30+
def isAdditiveNumber(self, num):
31+
"""
32+
:type num: str
33+
:rtype: bool
34+
"""
35+
def add(a, b):
36+
res, carry, val = "", 0, 0
37+
for i in xrange(max(len(a), len(b))):
38+
val = carry
39+
if i < len(a):
40+
val += int(a[-(i + 1)])
41+
if i < len(b):
42+
val += int(b[-(i + 1)])
43+
carry, val = val / 10, val % 10
44+
res += str(val)
45+
if carry:
46+
res += str(carry)
47+
return res[::-1]
48+
49+
50+
for i in xrange(1, len(num) - 1):
51+
for j in xrange(i + 1, len(num)):
52+
s1, s2 = num[0:i], num[i:j]
53+
if (len(s1) > 1 and s1[0] == '0') or \
54+
(len(s2) > 1 and s2[0] == '0'):
55+
continue
56+
57+
expected = add(s1, s2)
58+
cur = s1 + s2 + expected
59+
while len(cur) < len(num):
60+
s1, s2, expected = s2, expected, add(s2, expected)
61+
cur += expected
62+
if cur == num:
63+
return True
64+
return False

0 commit comments

Comments
 (0)