CLRS 练习 2.1-4 的 python 代码哪里出错了
Where am I going wrong in this python code for CLRS exercise 2.1-4
所以问题是:
"Consider a problem of adding two n-bit binary integers, stored in two n-element arrays A and B. The sum of the two integers should be stored in binary form in an (n+1)-element array C. State the problem formally and write pseudocode for adding the two integers."
我的 python 这个问题的代码是:
A = [1,0,1,1,0,1,0]
B = [1,1,1,0,1,0,0]
n = len(A)
C = [0,0,0,0,0,0,0,0]
for i in range(0, n):
C[i] = A[i] + B[i] + C[i]
if C[i] == 2:
C[i] = 0
C[i+1] == 1
elif C[i] == 3:
C[i] = 1
C[i+1] = 1
print C
我还取了左边的最低有效位,我可以在完成计算后取反。
我不知道错误是什么,请帮助!
C[i+1] == 1
进行比较,不 赋值。
以防万一,为了简洁起见,您希望稍作修改(伪代码):
for i = C.length to i = 2
C[i] = C[i] + A[i-1] + B[i-1]
if C[i] > 1
C[i-1] = C[i-1] + 1
C[i] = C[i] - 2
所以问题是: "Consider a problem of adding two n-bit binary integers, stored in two n-element arrays A and B. The sum of the two integers should be stored in binary form in an (n+1)-element array C. State the problem formally and write pseudocode for adding the two integers."
我的 python 这个问题的代码是:
A = [1,0,1,1,0,1,0]
B = [1,1,1,0,1,0,0]
n = len(A)
C = [0,0,0,0,0,0,0,0]
for i in range(0, n):
C[i] = A[i] + B[i] + C[i]
if C[i] == 2:
C[i] = 0
C[i+1] == 1
elif C[i] == 3:
C[i] = 1
C[i+1] = 1
print C
我还取了左边的最低有效位,我可以在完成计算后取反。
我不知道错误是什么,请帮助!
C[i+1] == 1
进行比较,不 赋值。
以防万一,为了简洁起见,您希望稍作修改(伪代码):
for i = C.length to i = 2
C[i] = C[i] + A[i-1] + B[i-1]
if C[i] > 1
C[i-1] = C[i-1] + 1
C[i] = C[i] - 2