题目
考虑把两个n位二进制整数加起来的问题,这两个整数分别存储在两个n元数组A和B中。这两个整数的和应按二进制形式存储在一个(n+1)元数组C中。请给出该问题的形式化描述,并写出伪代码。
找到的答案如下:
Input: An array of booleans A=⟨a1,a2,…,an⟩, an array of booleans B=⟨b1,b2,…,bn⟩, each representing an integer stored in binary format (each digit is a number, either 0 or 1, least-significant digit first) and each of length n.
Output: An array C=⟨c1,c2,…,cn+1⟩ that such that C′=A′+B′, where A′, B′ and C′ are the integers, represented by A, B and C.
pseudocode:
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数组的最右边是最高位,不懂。。。。留待解决
下面是我自己写的代码(Java):
package chapter2;
/* * 练习2.1-4 */
public class P214 {
public static void main(String[] args) {
int[] arr1={0,1,1,0};
int[] arr2={1,1,1,1};
int[] arr3=new int[5];
P214.addBinary(arr1, arr2, arr3);
}
public static void addBinary(int[] A,int[] B,int[] C){
int sum=0;
for(int i=A.length-1;i>=0;i--){
if((sum=A[i]+B[i])<2)
C[i+1]+=sum;
else{
C[i]+=1;
C[i+1]+=sum-2;
}
}
if(C[1]>=2){
C[0]+=1;
C[1]=C[1]-2;
}
for(int k:C)
System.out.print(k+" ");
}
}
运行结果:1 0 1 0 1