简体   繁体   中英

How to multiplay an array of Integers in Java

I have two arrays of integers and I want to multiply them together like the following:

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

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

I want to store them in a new array so that the product appears as:

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

I get how to do it with multiplying numbers like 2 x 24 since I can just push those into values into the product array. But when it comes to expanding beyond a single digit I am lost.

Why do you need to do this? Regardless, here is an example:

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)));
}

Notes: I have not bug tested this or run it through the JVM. Java isn't my usual programming language so I may have made a few mistakes. the "productArray" needs to be an ArrayList<> instead. I suspect that Integer.parseInt() is only for strings, so you may have to search for the char version of the function. Also, you need include Math...

int arr1num, arr2num, product;
multiplier = 1;
for (i = arr1.size();i>0;i--){
arr1num = arr1num + (arr1[i] * multiplier);
multiplier = multiplier * 10;
}

--do this also for the second array

-- now we have arr1num and arr2num as the numbers of both arrays and just get the product

product = arr1num * arr2num;

-- now store it in an array

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

number = product % divisor;
productArray.add(number);
divisor = divisor * 10;
}

You could use this (although it's not the best algorithm you could use to do this):

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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