0

我有两个整数数组,我想将它们相乘,如下所示:

int[] arr1 = {6, 1}; // This represents the number 16

int[] arr2 = {4, 2}; // This represents the number 24

我想将它们存储在一个新数组中,以便产品显示为:

int[] productArray = {4, 8, 3};

我知道如何通过乘以 2 x 24 之类的数字来做到这一点,因为我可以将这些值推入产品数组中。但是当涉及到超过个位数时,我迷失了。

4

3 回答 3

3

为什么需要这样做?无论如何,这里有一个例子:

int total1; // to find what the array represents in #
for (int c = 0; c < arr1.length() - 1; c++) {
 total1 += arr1[c] * Math.pow(10, (c+1)); // takes the number and adds it to the decimal number it should be
}
int total2;
for (int c = 0; c < arr2.length() - 1; c++) {
 total1 += arr2[c] * Math.pow(10, (c+1));
}
String s = Integer.toString(total2*total1);
for (int c = s.length()-1; c >= 0; c--) { // adds int to array backwards
  productArray.add(Integer.parseInt(s.atIndex(c)));
}

注意:我没有对此进行错误测试或通过 JVM 运行它。Java 不是我常用的编程语言,所以我可能犯了一些错误。“productArray”需要是一个 ArrayList<>。我怀疑 Integer.parseInt() 仅适用于字符串,因此您可能必须搜索该函数的 char 版本。此外,您需要包括数学...

于 2013-03-20T01:14:02.203 回答
3
int arr1num, arr2num, product;
multiplier = 1;
for (i = arr1.size();i>0;i--){
arr1num = arr1num + (arr1[i] * multiplier);
multiplier = multiplier * 10;
}

--对第二个数组也这样做

-- 现在我们将 arr1num 和 arr2num 作为两个数组的编号,然后得到乘积

product = arr1num * arr2num;

-- 现在将它存储在一个数组中

int divisor = 10;
int number;
for(i=0;i<int.length();i++){

number = product % divisor;
productArray.add(number);
divisor = divisor * 10;
}
于 2013-03-20T01:25:33.107 回答
1

您可以使用它(尽管它不是您可以用来执行此操作的最佳算法):

public static int[] multiplyArrays(int[] a, int[] b){
    //turns arrays into integers
    String num1 = "";
    for (int i = a.length - 1; i > -1; i--){
        num1 += a[i];
    }

    String num2 = "";
    for (int i = b.length - 1; i > -1; i--){
        num2 += b[i];
    }

    //does calculation
    char[] answer = Integer.toString(Integer.parseInt(num1) * Integer.parseInt(num2)).toCharArray();

    //converts char array into int array
    int[] answer2 = new int[answer.length];

    for (int i = 0; i < answer.length; i++){
        answer2[answer.length - i - 1] = Integer.parseInt(String.valueOf(answer[i]));
    }

    return answer2;
}
于 2013-03-20T01:29:51.890 回答