在Java中添加二进制数

时间:2014-12-03 14:11:35

标签: java arrays algorithm binary decimal

我有一个函数,它将两个二进制数作为整数数组,添加数字,然后将总和作为一个新的整数数组返回。

public static int[] addBin(int a[], int b[]){
      int[] sum = {0, 0, 0, 0, 0, 0, 0, 0};
      int carryover = 0;
      int randombanana = 0;
      int x = 7;
      for(x = 7; x > 0; x--){
        randombanana = a[x] + a[x] + carryover;
        if(randombanana == 1){
          sum[x] = 1;
          carryover = 0;
        }
        else if(randombanana == 2){
          sum[x] = 0;
          carryover = 1;
        }
        else if(randombanana == 3){
          sum[x] = 1;
          carryover = 1;
        }
        else if(randombanana == 0){
          sum[x] = 0;
          carryover = 0;
        }
        else{
          System.out.println("Either I [censored] up, or you [censored] up.  I'm a genius so I'm going to assume you [censored] up");
        }
      }
          if(carryover == 1){
            sum[x] = 1;
      }
      return sum;
    }

代码在单位数字上工作正常,包括需要携带数字的数字,但是当数字被添加到自身时它会起作用的双位或三位数字,但是当添加不同的多位数字时则不行。

3 个答案:

答案 0 :(得分:0)

应该是

randombanana = a[x] + b[x] + carryover;

答案 1 :(得分:0)

你的for循环没有处理第0位

for(x = 7; x >= 0; x--){

答案 2 :(得分:0)

假设两个数字的长度相同,则可以按如下所示添加数字:

public static int[] addNumbers(int[] firstNum, int[] secondNum) {
        int[] result = new int[firstNum.length + 1];
        int digitSum, carry = 0, i;
        for (i = firstNum.length - 1; i >= 0; i--) {
            digitSum = firstNum[i] + secondNum[i] + carry;
            result[i + 1] = digitSum % 2;
            carry = digitSum / 2;
        }
        result[0] = carry;
        return result;
    }