首页 > 解决方案 > 乘以Java中表示为数组的数字?

问题描述

我必须编写一个函数,将由两个 int 数组表示的两个数字相乘(所以我不能使用 ArrayLists 或其他东西)。

数字的每个数字都由int数组中的 0 到 9 表示,任何元素都不应大于该数字。

数组的第一个元素代表数字的最后一位,依此类推,因此该数字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)));
    }

}

标签: javaarraysmultiplication

解决方案


也许这是因为您在 times() 方法的 for 循环中的索引正在递增和递减。i 下降,j 上升。此外,在第二个 for 循环中,您应该只递增到“a.length - 1”,而不是“a.length”。


推荐阅读