/** * Created by zqx on 16/8/25. */ public class BinaryOperation { private static final int MAX = 10; public static void main(String[] args) { int[] A = {0,1,1,1,0,1,0,1,1,1}; int[] B = {1,0,0,0,1,0,1,1,0,1}; int[] C = new int[MAX+1]; add(A,B,C); for (int value : C){ System.out.print(value); } } /** * * @param A 数组1 * @param B 数组2 * @param C 结果数组3 length 等于 A或B的length +1; * @return C = A + B */ public static int[] add(int[] A,int[] B,int[] C){ int carry = 0; for (int i = A.length;i>0;i--){ int result = A[i-1] + B[i-1] + carry; C[i] = result % 2; carry = result > 1 ? 1 : 0; } C[0] = carry; return C; } }
考虑把两个n位二进制整数加起来的问题,这两个整数分别存储在两个n元数组A和B中,这两个整数的和应按二进制形式存储在一个(n+1)元数组C中。