我必须编写一个函数,将两个 int 数组表示的两个数字相乘(所以我不能使用 ArrayLists 或其他东西)。
数组中数字的每个数字都由 0 到 9 之间的 int
表示,任何元素都不能大于该值。
数组的第一个元素代表数字的最后一位数字,依此类推,因此数字 1234
将是 {4,3,2,1}
如下该函数中的一个数组。
我认为以这种方式乘以这些数组类似于长乘法,所以我尝试以类似的方式实现它:将第一个数组的每个数字与第二个数组的每个数字相乘,并存储其余的如果结果等于或大于 10,然后将其添加到下一个数字。然而,我似乎在代码中做错了一些事情(也许是其余部分的计算?),因为我的函数结果不正确:我用190乘以86(用数组{0, 9,1}
和 {6,8}
)并得到 15342
({2,4,3,5,1}
) 而不是实际结果 16340
(即 {0,4,3,6,1}
)。
有人可以帮我解决这个问题吗?这是我的代码:
import java.util.Arrays;
public class MultiplyArrays {
static int[ ] times(int[ ] a, int[ ] b) {
int[] arr = new int[a.length + b.length - 1];//arr should be the result of a*b. The result shouldn't be shorter than that
int tmp = 0;//stores the rest of two-digit numbers
for(int i = b.length - 1; i >= 0; i--){
for(int j = 0; j < a.length; j++){//should multiply all digits of a with the current index of b
arr[i + j] = (arr[i + j] + (b[i] * a[j] + tmp)) % 10;//sets the value of the (i+j)th index in arr to the multiplication of two numbers from a and b adding the rest tmp.
if((arr[i + j] + b[i] * a[j] + tmp) < 10){//if this number is less than 10, there is no rest
tmp = 0;
}
else{//otherwise, the rest should be the second digit
tmp = (((arr[i + j] + (b[i] * a[j] + tmp))) - ((arr[i + j] + (b[i] * a[j] + tmp)) % 10)) / 10;//something in the formula for the rest is wrong, I guess
}
}
}
if(tmp != 0){//if the last number of the array containing the result is calculated and there still is a rest, a new array with one more digit is created
int[] arr2 = new int[arr.length + 1];
for(int i = arr.length - 1; i >= 0; i--){//the new array copies all numbers from the old array
arr2[i] = arr[i];
arr2[arr2.length - 1] = tmp;//the last space is the rest now
}
return arr2;
}
else{//if there is no rest after calculating the last number of arr, a new array isn't needed
return arr;
}
}
public static void main(String[] args) {//test the function with 190 * 86
int[] a = {0,9,1};
int[] b = {6,8};
System.out.println(Arrays.toString(times(a,b)));
}
}
最佳答案
也许这是因为 times() 方法的 for 循环中的索引正在递增和递减。 i 下降,j 上升。 另外,在第二个 for 循环中,您应该只增加到“a.length - 1”,而不是“a.length”。
关于java - 在Java中用数组表示的数字相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59229647/