两个n 位的二进制数据的相加问题
Consider the problem:
add 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.
The problem can be formally stated as:
Input: Two n-bit binary integers stored in two nn-element array of binary digits (either 0 or 1) A=〈a1,a2,...,an〉 and B=〈b1,b2,...,bn〉.
Output: A (n+1)-bit binary integer stored in (n+1)-element array of binary digits (either 0 or 1) C=〈c1,c2,...,cn+1〉such that C=A+B.
Binary——add(A,B)的伪代码写法:(伪代码代表不可以直接运行需要进行相应的具体编程环境的书写更改)
n = A.length
// A and B have the same length
for i = 1 to (n + 1)
C[i] = 0
// initiation the C
carry = 0
// gain initiate
for i = n down to 1
C[i] = (A[i] + B[i] + carry) % 2
carry = (A[i] + B[i] + carry) / 2
C[i] = carry
return C
Note: As we are adding number represented in binary, we have to start bit by bit addition from the least significant digit.