Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
additive-number.py 1.17 KB
一键复制 编辑 原始数据 按行查看 历史
Allen Liu 提交于 2018-10-13 13:15 +08:00 . remove unused code
# Time: O(n^3)
# Space: O(n)
class Solution(object):
def isAdditiveNumber(self, num):
"""
:type num: str
:rtype: bool
"""
def add(a, b):
res, carry, val = "", 0, 0
for i in xrange(max(len(a), len(b))):
val = carry
if i < len(a):
val += int(a[-(i + 1)])
if i < len(b):
val += int(b[-(i + 1)])
carry, val = val / 10, val % 10
res += str(val)
if carry:
res += str(carry)
return res[::-1]
for i in xrange(1, len(num)):
for j in xrange(i + 1, len(num)):
s1, s2 = num[0:i], num[i:j]
if (len(s1) > 1 and s1[0] == '0') or \
(len(s2) > 1 and s2[0] == '0'):
continue
expected = add(s1, s2)
cur = s1 + s2 + expected
while len(cur) < len(num):
s1, s2, expected = s2, expected, add(s2, expected)
cur += expected
if cur == num:
return True
return False
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助