我有两个整数数组,我想将它们相乘,如下所示:
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 之类的数字来实现这一点,因为我可以将这些值插入乘积数组中。但当涉及到超出一位数时,我迷失了。
最佳答案
为什么需要这样做?不管怎样,这里有一个例子:
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 版本。另外,您需要包括数学...
关于java - 如何在 Java 中将整数数组相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15513489/