当然可以,你应该已经意识到,只要你说你可以得到[1,0,0,0,0,0,0]。所以很明显,问题不在于得到多余的数字,而是保留多余的数字。
如果没有看到您的代码,我们实际上无法告诉您它有什么问题(有一定程度的确定性),但您会发现您可以根据下面的代码。一、强制初始化:
class Zillion:
# Init: simply set to zero.
def __init__(self):
self.data = [0]
现在,增加一个数字的代码。它简单地使用了任何像样的小学教授的算法:
# Increment the number.
def increment(self):
# Force 1 to be added initially.
carry = 1
# Iterate over digits in reverse.
for index in range(len(self.data) - 1,-1,-1):
# Add current carry and set new carry based on result.
self.data[index] = self.data[index] + carry
if self.data[index] == 10:
self.data[index] = 0
carry = 1
else:
carry = 0
# If carry at end then there was overflow, insert 1 at left.
if carry == 1:
self.data.insert(0,1)
然后只是一些测试工具代码,以便您可以看到它的实际效果:
# Code for debugging.
def output(self):
print self.data
# Test code here, show various increments.
if __name__ == "__main__":
z = Zillion()
for x in range(8): # -> 8
z.increment()
for x in range(13): # -> 21
z.output()
z.increment()
z.output()
print "==="
for x in range(999977): # -> 999,998
z.increment()
for x in range(13): # -> 1,000,011
z.output()
z.increment()
z.output()
运行该代码可让您确信列表的长度会发生变化并正确维护:
[8]
[9]
[1, 0]
[1, 1]
[1, 2]
[1, 3]
[1, 4]
[1, 5]
[1, 6]
[1, 7]
[1, 8]
[1, 9]
[2, 0]
[2, 1]
===
[9, 9, 9, 9, 9, 8]
[9, 9, 9, 9, 9, 9]
[1, 0, 0, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0, 1]
[1, 0, 0, 0, 0, 0, 2]
[1, 0, 0, 0, 0, 0, 3]
[1, 0, 0, 0, 0, 0, 4]
[1, 0, 0, 0, 0, 0, 5]
[1, 0, 0, 0, 0, 0, 6]
[1, 0, 0, 0, 0, 0, 7]
[1, 0, 0, 0, 0, 0, 8]
[1, 0, 0, 0, 0, 0, 9]
[1, 0, 0, 0, 0, 1, 0]
[1, 0, 0, 0, 0, 1, 1]