下面的python块应该添加两个二进制数字字符串。变量res_str
和carry
在循环的每次迭代中都被重置为它们的初始值。你知道吗
class Solution:
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if len(a) < len(b):
a.zfill(len(b))
elif len(a) > len(b):
b.zfill(len(a))
res_str = ''
carry = '0'
for asub, bsub in reversed(list(zip(a, b))):
print(res_str, carry)
if asub == '1' and bsub == '1':
res_str = '0' + res_str
carry = '1' + carry
elif asub == '1' or bsub == '1':
res_str = '1' + res_str
carry = '0' + carry
else:
res_str = '0' + res_str
carry = '0' + carry
print(res_str, carry)
if '1' in carry:
return self.addBinary(res_str, carry)
else:
return res_str
s = Solution()
s.addBinary('1', '11')
# 0
# 0 10
# 0
# 1 00
# 1
在循环的每次迭代开始时,它们的值分别是''
和0
。它们的值在循环块期间被改变,但它们被重置。你知道吗
我试着用同样的结果将它们改为类变量(self.res_str
和self.carry
)。你知道吗
是什么导致这些变量被重置?你知道吗
编辑:忘记使用zfill
的输出
目前没有回答
相关问题 更多 >
编程相关推荐