0

So the problem is: "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."

and my python code for this problem is:

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

Also I have taken the least significant digits on the left which I can reverse after I've done the calculation.

I cant figure out what the mistake is please help!

  • Just a note: If you plan on having A & B taken in via input, an easier way to define `C` would be `C=[0]*(n+1)`, which auto generates the array you want. – Emad Y Jul 08 '15 at 18:55

2 Answers2

5

C[i+1] == 1 does a comparison, not an assignment.

jtbandes
  • 115,675
  • 35
  • 233
  • 266
0

In case, you like a slight modification for the sake of brevity (pseudocode):

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
ksha
  • 2,007
  • 1
  • 19
  • 22