2.1-4 有两个各存放在数组A和B中的n位二进制整数,考虑它们的相加问题。两个整数的和以二进制形式存放在具有(n+1)个元素的数组C中。请给出这个问题的形式化描述,并写出伪代码。
自己写的java解决方案。没有找到标准答案,先放上来吧,不一定很好。不过运行结果正确。
package mytest;
public class BinaryAdd {
public int lastflow = 0;// 用来存放上次溢出
// 用来处理二进制的加法
public int addMethod(int a, int b) {
int r = a + b + lastflow;
if (r > 1) {// 如果结果为2或3,最多为3;说明溢出了
lastflow = 1;
return r % 2;
} else {
lastflow = 0;
return r;
}
}
public static void main(String[] args) throws Exception {
final int n = 10;
int[] A = { 1, 1, 0, 0, 1, 0, 1, 1, 1, 0 };
int[] B = { 1, 1, 1, 0, 1, 1, 0, 1, 1, 1 };
int[] C = new int[n + 1];// 默认的是0
BinaryAdd binaryAdd = new BinaryAdd();
for (int i = n - 1; i >= 0; --i) {
C[i + 1] = binaryAdd.addMethod(A[i], B[i]);
}
C[0] = binaryAdd.lastflow;
for (int j = 0; j < n + 1; ++j) {
System.out.print(C[j]);
}
}
}