考虑把两个n位二进制整数加起来,这两个整数分别存储在两个n元数组A和B中,这两个整数的和应按二进制形式存储在一个n+1元数组中。
伪代码:
ADD-BINARY(A, B):
C = new integer[A.length + 1]
carry = 0
for i = 1 to A.length
C[i] = (A[i] + B[i] + carry) % 2 // remainder
carry = (A[i] + B[i] + carry) / 2 // quotient
C[i] = carry
return C
C++代码:
void Add_Binary()
{
int A[5] = { 0, 1, 1, 0, 0 };
int B[5] = { 1, 1, 0, 1, 0 };
int C[6];
int carry = 0;
int i;
for (i = 4; i >=0; --i)
{
C[i+1] = (A[i] + B[i] + carry) % 2;
carry = (A[i] + B[i] + carry) / 2;
}
C[i+1] = carry;
}
可以用于两个大数相加,(a+b+carry)%2为余数,(a+b+carry)/2为商,其中carry为进位。
来自算法导论