简体   繁体   English

如何将具有不同位数的整数的数组表示形式相加?

[英]How to add together an array representation of an integer with different number of digits?

How would I add together two integers with different number of digits, using an array, without causing an out of bounds exception? 如何使用数组将两个具有不同位数的整数相加在一起,而不会导致超出范围的异常?

For example: 500 + 99 each digit is an element of the array 例如:500 + 99每个数字是数组的元素

This is how I'm doing it right now: 这就是我现在正在做的事情:

 int aIILength = infiniteInteger.length-1;
 int bIILength = anInfiniteInteger.infiniteInteger.length-1;
 for(int f = aIILength; f >0; f--){

        int aTempNum = infiniteInteger[f];


        int bTempNum = anInfiniteInteger.infiniteInteger[f];

        result = aTempNum + bTempNum;

        //array representation of sum
        tempArray[f] = result;

    }

Let the counter in the loop go from 1 and up, and use it to access the digits from the end of each array. 让循环中的计数器从1开始向上移动,并使用它从每个数组的末尾访问数字。

You need a carry to hold the overflow of adding each set of digits. 您需要一个进位来保持添加每组数字的溢出。

Loop until you run out of digits in both arrays, and carry is zero. 循环直到两个数组中的数字用完,并且进位为零。

Check the range when you access the digits from the arrays, and use zero when you run out of digits. 当您从数组访问数字时,请检查范围;当数字用完时,请使用零。

int aIILength = infiniteInteger.length;
int bIILength = anInfiniteInteger.infiniteInteger.length;
int carry = 0;
for(int f = 1; f <= aIILength || f <= bIILength || carry > 0; f++){
  int aTempNum;
  if (f <= aIILength) {
    aTempNum = infiniteInteger[aIILength - f];
  } else {
    aTempNum = 0;
  }
  int bTempNum;
  if (f <= bIILength) {
    bTempNum = anInfiniteInteger.infiniteInteger[bIILength - f];
  } else {
    bTempNum = 0;
  }
  result = aTempNum + bTempNum + carry;
  tempArray[tempArray.length - f] = result % 10;
  carry = result / 10;
}

Note: Make tempArray longer than both the operand arrays, so that it has place for a potential carry to the next digit. 注意:使tempArray长度比两个操作数数组的长度都长,以便它有可能带入下一位数字。

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

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