简体   繁体   English

逐个元素地在数组中添加数字

[英]Adding numbers in arrays element by element

The goal is to add two numbers together that are stored in arrays-element by element. 目标是将两个数字相加,这些数字一元一元地存储在数组中。 The numbers do not necessarily need to be of equal length. 数字不一定需要具有相同的长度。 I am having trouble accounting for the possibility of a carry over. 我无法解释结转的可能性。

If the number is 1101 it would be represented : [1,0,1,1]- The least significant bit is at position 0. I am doing the addition without converting it to an integer. 如果数字是1101,则表示为:[1,0,1,1] - 最低有效位在位置0.我正在进行加法而不将其转换为整数。

I am making a separate method to calculate the sum of binary numbers but I just want to understand how to go about this using the same logic. 我正在制作一个单独的方法来计算二进制数的总和,但我只想了解如何使用相同的逻辑来解决这个问题。

Ex: 349+999 or they could even be binary numbers as well such as 1010101+11 例如: 349 + 999或者它们甚至可以是二进制数,例如1010101 + 11

Any suggestions? 有什么建议?

    int carry=0;
    int first= A.length;
    int second=B.length;
    int [] sum = new int [(Math.max(first, second))];
    if(first > second || first==second)
    {
        for(int i =0; i <A.length;i++)
        {
            for(int j =0; j <B.length;j++)
            {
                sum[i]= (A[i]+B[j]);
            }
        }
        return sum; 
    }
    else 
    {
        for(int i =0; i <B.length;i++)
        {
            for(int j =0; j <A.length;j++)
            {
                sum[i]= (A[i]+B[j]);
            }
        }
        return sum;
    }

For the binary addition: 对于二进制加法:

   byte carry=0;
    int first= A.length;
    int second=B.length;
    byte [] sum = new byte [Math.max(first, second)+1];
    if(first > second || first==second)
    {
        for(int i =0; i < A.length && i!= B.length ;i++)
        {
            sum[i]= (byte) (A[i] + B[i] + carry);
            if(sum[i]>1) {
                sum[i] = (byte) (sum[i] -1);
                carry = 1;
            }
            else
                carry = 0;
        }
        for(int i = B.length; i < A.length; i++) {
           sum[i] = (byte) (A[i] + carry);
           if(sum[i]>1) {
                sum[i] = (byte) (sum[i] -1);
                carry = 1;
            }
            else
                carry = 0;
       }
        sum[A.length] = carry; //Assigning msb as carry
        return sum; 
    }
    else 
    { 
        for(int i =0; i < B.length && i!= A.length ;i++) {
            sum[i]= (byte) (A[i] + B[i] + carry);
            if(sum[i]>1) {
                sum[i] = (byte) (sum[i] -1);
                carry = 1;
            }
            else
                carry = 0;
        }
        for(int i = A.length; i < B.length; i++) {
           sum[i] = (byte) (B[i] + carry);
           if(sum[i]>1) {
                sum[i] = (byte) (sum[i] -1);
                carry = 1;
            }
            else
                carry = 0;
       }
        sum[B.length] = carry;//Assigning msb as carry
        return sum; 
    }

There is no need to treat binary and decimal differently. 不需要以不同方式处理二进制和十进制。 This handles any base, from binary to base36, and extremely large values -- far beyond mere int's and long's! 这可以处理从二进制到base36的任何基数,以及非常大的值 - 远远超出了int和long的范围!

Digits need to be added from the least significant first. 首先需要从最不重要的位置添加数字。 Placing the least significant digit first makes the code simpler, which is why most CPUs are Little-Endian. 首先放置最低有效数字会使代码更简单,这就是大多数CPU都是Little-Endian的原因。

Note: Save the code as "digits.java" -- digits is the main class. 注意:将代码保存为“digits.java” - 数字是主类。 I put Adder first for readability. 为了便于阅读,我首先添加了Adder。

Output: 输出:

NOTE: Values are Little-Endian! (right-to-left)
base1: 0(0) + 00(0) = 000(0)
base2: 01(2) + 1(1) = 110(3)
base2: 11(3) + 01(2) = 101(5)
base2: 11(3) + 011(6) = 1001(9)
base16: 0A(160) + 16(97) = 101(257)
base32: 0R(864) + 15(161) = 101(1025)

Source code: digits.java: 源代码:digits.java:

class Adder {
  private int base;
  private int[] a;
  private int[] b;
  private int[] sum;

  public String add() {
    int digitCt= a.length;
    if(b.length>digitCt)
      digitCt= b.length;        //max(a,b)
    digitCt+= 1;                //Account for possible carry
    sum= new int[digitCt];      //Allocate space
    int digit= 0;               //Start with no carry
    //Add each digit...
    for(int nDigit=0;nDigit<digitCt;nDigit++) {
      //digit already contains the carry value...
      if(nDigit<a.length)
        digit+= a[nDigit];
      if(nDigit<b.length)
        digit+= b[nDigit];
      sum[nDigit]= digit % base;//Write LSB of sum
      digit= digit/base;        //digit becomes carry
    }
    return(arrayToText(sum));
  }

  public Adder(int _base) {
    if(_base<1) {
      base= 1;
    } else if(_base>36) {
      base=36;
    } else {
      base= _base;
    }
    a= new int[0];
    b= new int[0];
  }

  public void loadA(String textA) {
    a= textToArray(textA);
  }

  public void loadB(String textB) {
    b= textToArray(textB);
  }

  private int charToDigit(int digit) {
    if(digit>='0' && digit<='9') {
      digit= digit-'0';
    } else if(digit>='A' && digit<='Z') {
      digit= (digit-'A')+10;
    } else if(digit>='a' && digit<='z') {
      digit= (digit-'a')+10;
    } else {
      digit= 0;
    }
    if(digit>=base)
      digit= 0;
    return(digit);
  }

  private char digitToChar(int digit) {
    if(digit<10) {
      digit= '0'+digit;
    } else {
      digit= 'A'+(digit-10);
    }
    return((char)digit);
  }

  private int[] textToArray(String text) {
    int digitCt= text.length();
    int[] digits= new int[digitCt];
    for(int nDigit=0;nDigit<digitCt;nDigit++) {
      digits[nDigit]= charToDigit(text.charAt(nDigit));
    }
    return(digits);
  }

  private String arrayToText(int[] a) {
    int digitCt= a.length;
    StringBuilder text= new StringBuilder();
    for(int nDigit=0;nDigit<digitCt;nDigit++) {
      text.append(digitToChar(a[nDigit]));
    }
    return(text.toString());
  }

  public long textToInt(String a) {
    long value= 0;
    long power= 1;
    for(int nDigit=0;nDigit<a.length();nDigit++) {
      int digit= charToDigit(a.charAt(nDigit));
      value+= digit*power;
      power= power*base;
    }
    return(value);
  }
}

public class digits {

  public static void main(String args[]) {
    System.out.println("NOTE: Values are Little-Endian! (right-to-left)");
    System.out.println(test(1,"0","00"));
    System.out.println(test(2,"01","1"));
    System.out.println(test(2,"11","01"));
    System.out.println(test(2,"11","011"));
    System.out.println(test(16,"0A","16"));
    System.out.println(test(32,"0R","15"));
  }

  public static String test(int base, String textA, String textB) {
    Adder adder= new Adder(base);
    adder.loadA(textA);
    adder.loadB(textB);
    String sum= adder.add();
    String result= String.format(
      "base%d: %s(%d) + %s(%d) = %s(%d)",
       base,
       textA,adder.textToInt(textA),
       textB,adder.textToInt(textB),
       sum,adder.textToInt(sum)
    );
    return(result);
  }

}

First off, adding binary numbers will be different then ints. 首先,添加二进制数将不同于整数。 For ints you could do something like 对于整数,你可以做类似的事情

int first = A.length;
int second = B.length;

int firstSum = 0;
for (int i = 0; i < first; i++){
    firstSum += A[i] * (10 ^ i);
}

int secondSum = 0;
for (int j = 0; j < second; j++){
    secondSum += B[j] * (10 ^ j);
}

int totalSum = firstSum + secondSum;

It should be represented like this in below as we have to add only the values at same position of both the arrays. 它应该在下面表示如下,因为我们只需要在两个数组的相同位置添加值。 Also, in your first if condition, it should be || 此外,在您的第一个if条件中,它应该是|| instead of && . 而不是&& This algorithm should perfectly work. 这个算法应该完美的工作。 Let me know if there are any complications. 如果有任何并发​​症,请告诉我。

int carry=0;
int first= A.length;
int second=B.length;
int [] sum = new int [Math.max(first, second)+1];
if(first > second || first==second)
{
    for(int i =0; i < A.length && i!= B.length ;i++)
    {
        sum[i]= A[i] + B[i] + carry;
        if(sum[i]>9) {
            sum[i] = sum[i] -9;
            carry = 1;
        }
        else
            carry = 0;
    }
    for(int i = B.length; i < A.length; i++) {
       sum[i] = A[i] + carry;
       if(sum[i]>9) {
            sum[i] = sum[i] -9;
            carry = 1;
        }
        else
            carry = 0;
   }
    sum[A.length] = carry; //Assigning msb as carry
    return sum; 
}
else 
{ 
    for(int i =0; i < B.length && i!= A.length ;i++) {
        sum[i]= A[i] + B[i] + carry;
        if(sum[i]>9) {
            sum[i] = sum[i] -9;
            carry = 1;
        }
        else
            carry = 0;
    }
    for(int i = A.length; i < B.length; i++) {
       sum[i] = B[i] + carry;
       if(sum[i]>9) {
            sum[i] = sum[i] -9;
            carry = 1;
        }
        else
            carry = 0;
   }
    sum[B.length] = carry //Assigning msb as carry
    return sum; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM