Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string multiplication

Tags:

java

algorithm

I am trying to multiply two strings, but I am getting the wrong answer. Any help will be appreciated:

public class stringmultiplication {
    public static void main(String[] args) {
        String s1 = "10";
        String s2 = "20";
        int num = 0;
        for(int i = (s1.toCharArray().length); i > 0; i--)
            for(int j = (s2.toCharArray().length); j > 0; j--)
                num = (num * 10) + ((s1.toCharArray()[i - 1] - '0') * (s2.toCharArray()[j - 1] - '0'));
        System.out.println(num);
    }
}
like image 661
Jony Avatar asked Aug 06 '26 00:08

Jony


2 Answers

public static void main(String[] args) {
        String number1 = "108";
        String number2 = "84";

        char[] n1 = number1.toCharArray();
        char[] n2 = number2.toCharArray();

        int result = 0;

        for (int i = 0; i < n1.length; i++) {
            for (int j = 0; j < n2.length; j++) {
                result += (n1[i] - '0') * (n2[j] - '0')
                        * (int) Math.pow(10, n1.length + n2.length - (i + j + 2));
            }
        }
        System.out.println(result);
    }

This one should be correct implementation without using integers.

like image 95
Petro Semeniuk Avatar answered Aug 07 '26 14:08

Petro Semeniuk


You're multiplying the numbers digit-wise, and you're not handling the powers of 10 correctly.

You need to first parse the strings into integers. You're on the right track here. You can simplify the loop indices, and you only have to call toCharArray once. E.g.:

After parsing, you can multiply the integers.

EDIT: If that's not allowed, you need to implement an algorithm like this one, which is a bit more complicated.

One approach is to make an (n + 1) x (m + n) array (strictly an array of arrays), where m and n are the number of digits in each. It will be initialized to 0, and you can use this as an area to put the rows of the immediate and final results. These are then summed with carry. This is obviously a näive algorithm.

E.g. for the example above:

int[][] intermediates = new int[3][4];

This is an upper bound.

like image 29
Matthew Flaschen Avatar answered Aug 07 '26 14:08

Matthew Flaschen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!