【发布时间】:2017-01-26 03:09:31
【问题描述】:
当程序执行第二个if并更改P = 0时,它将执行下一个if。我知道这是错误的,但我很好奇如何保持变量 (P) 不变并且不影响 if 语句中的其他变量。
"""
:type a: str
:type b: str
:rtype: str
"""
class Solution(object):
def addBinary(self, a, b):
c = ''
P = 0
for i,j in zip(range(len(a)-1, -1, -1),range(len(b)-1, -1, -1)):
if a[i] + b[j] == '11':
c = c + '0'
P = 1
if a[i] + b[j] == '10' or a[i] + b[j] == '01' and P == 1:
c = c + '0'
P = 0
if a[i] + b[j] == '10' or a[i] + b[j] == '01' and P == 0:
c = c + '1'
if a[i] + b[j] == '00' and P == 1:
c = c + '1'
P =0
if a[i] + b[j] == '00' and P == 0:
c = c + '0'
T = len(a) - len(b)
if T > 0:
c = c + a[:T]
else:
c = c + b[:T]
return c[::-1]
【问题讨论】:
标签: python if-statement conditional-statements