파이썬에서 간단한 바이너리 추가 프로그램을 작성하려고합니다. 파이썬이 이미 그것을 할 수 있다는 것을 알고 있습니다. 기본적인 컴퓨팅 개념을 연습하기 위해 노력하고 있습니다.프로그램 추가가 작동하지 않습니다.
#Binary Adding Machine
def add(a,b):
#create empty variables
result=""
state=0
#equalize string lengths
if a>=b:
c=a
b="0"*(len(a)-len(b))+b
else:
c=b
a="0"*(len(b)-len(a))+a
#add strings together into result, in reverse order
for i in range(1,(len(c)+1)):
if state==0:
if a[-i]==b[-i]=="0":
result+="0"
state=0
elif ((a[-i]=="0" and b[-i]=="1") or (a[-i]=="1" and b[-i]=="0")):
result+="1"
state=0
elif a[-i]==b[-i]=="1":
result+="0"
state=1
elif state==1:
if a[-i]==b[-i]=="0":
result+="1"
state=0
elif ((a[-i]=="0" and b[-i]=="1") or (a[-i]=="1" and b[-i]=="0")):
result+="0"
state=1
elif a[-i]==b[-i]=="1":
result+="1"
state=1
#add another "1" if final state is 1
if state==1:
result+="1"
state=0
#reverse string
return result[::-1]
print(add("110101","1111010"))
print(add("1","100000"))
print(add("1","1"))
print(add("100","100"))
print(add("000100100","100"))
print(add("100100100","100"))
당신이 만약 : 나는 이상한 유일한 것은 숫자 중 하나가 더 이상 다른보다 0에서 시작하는 경우, 프로그램이 예상 된 결과를 반환하지 않는다는 것입니다 꽤 잘 작동있어 다음 번호가 인쇄됩니다 프로그램 실행 : 마지막 줄에
10101111
100001
10
1000
1000
100101000
두 번째 000101000
를 반환해야합니다을 대신 그것은 1000
를 반환합니다. 하지만 우리가 마지막 줄에서 볼 수 있듯이 숫자가 1에서 시작하면 제대로 작동합니다.
왜 이런 일이 발생하는지 알고 있습니까?
대단히 감사합니다.