Java JavaScript Php Python

Multiply two strings  with example JAVA, PHP, JS, PYTHON

Given two positive numbers as strings. The numbers may be very large (may not fit in long long int), the task is to find product of these two numbers.

Examples: 

Input : num1 = 4154  

         num2 = 51454

Output : 213739916 

Input : num1 = 654154154151454545415415454  

          num2 = 63516561563156316545145146514654 

Output : 41549622603955309777243716069997997007620439937711509062916

The concept is based on elementary school maths.

We begin by multiplying the last digit of the second number by the first number. The second digit of the second number is then multiplied by the first number, and so on. All of these multiplications are added together. We shifted the i-th multiplication when adding.

The strategy employed in the following solution is to keep the result in a single array. In a loop, we go over all of the digits in the first and second numbers and add the result at the proper point.

JAVA

// Java program to multiply two numbers

// represented as Strings.

class GFG

{

// Multiplies str1 and str2, and prints result.

static String multiply(String num1, String num2)

{

    int len1 = num1.length();

    int len2 = num2.length();

    if (len1 == 0 || len2 == 0)

        return “0”;

    // will keep the result number in vector

    // in reverse order

    int result[] = new int[len1 + len2];

    // Below two indexes are used to

    // find positions in result.

    int i_n1 = 0;

    int i_n2 = 0;

    // Go from right to left in num1

    for (int i = len1 – 1; i >= 0; i–)

    {

        int carry = 0;

        int n1 = num1.charAt(i) – ‘0’;

        // To shift position to left after every

        // multipliccharAtion of a digit in num2

        i_n2 = 0;

        // Go from right to left in num2            

        for (int j = len2 – 1; j >= 0; j–)

        {

            // Take current digit of second number

            int n2 = num2.charAt(j) – ‘0’;

            // Multiply with current digit of first number

            // and add result to previously stored result

            // charAt current position.

            int sum = n1 * n2 + result[i_n1 + i_n2] + carry;

            // Carry for next itercharAtion

            carry = sum / 10;

            // Store result

            result[i_n1 + i_n2] = sum % 10;

            i_n2++;

        }

        // store carry in next cell

        if (carry > 0)

            result[i_n1 + i_n2] += carry;

        // To shift position to left after every

        // multipliccharAtion of a digit in num1.

        i_n1++;

    }

    // ignore ‘0’s from the right

    int i = result.length – 1;

    while (i >= 0 && result[i] == 0)

    i–;

    // If all were ‘0’s – means either both

    // or one of num1 or num2 were ‘0’

    if (i == -1)

    return “0”;

    // genercharAte the result String

    String s = “”;

    while (i >= 0)

        s += (result[i–]);

    return s;

}

// Driver code

public static void main(String[] args)

{

    String str1 = “123542”;

    String str2 = “171454”;

    if ((str1.charAt(0) == ‘-‘ || str2.charAt(0) == ‘-‘) &&

        (str1.charAt(0) != ‘-‘ || str2.charAt(0) != ‘-‘))

        System.out.print(“-“);

    if (str1.charAt(0) == ‘-‘)

        str1 = str1.substring(1);

    if (str2.charAt(0) == ‘-‘)

        str2 = str2.substring(1);

    System.out.println(multiply(str1, str2));

}

}

PHP

<?php

// PHP program to illustrate bcmul() function

// input numbers with arbitrary precision

$num_str1 = “3”;

$num_str2 = “11.222”;

// calculates the multiplication of the two

// numbers when $scaleVal is not specified

$res = bcmul($num_str1, $num_str2);

echo $res;

?>

JS

function multiply(a, b) {

    const product = Array(a.length+b.length).fill(0);

    for (let i = a.length; i–; null) {

        let carry = 0;

        for (let j = b.length; j–; null) {

            product[1+i+j] += carry + a[i]*b[j];

            carry = Math.floor(product[1+i+j] / 10);

            product[1+i+j] = product[1+i+j] % 10;

        }

        product[i] += carry;

    }

    return product.join(“”).replace(/^0*(\d)/, “$1”);

}

console.log(multiply(“123456789”, “987654321”));

PYTHON

def multiply_two_strings(a,b):

   # code here

   # return the product string

   product = int(a) * int(b)

   return(product)

t=int(input(‘Enter the number of pairs to be multiplied: ‘))

for i in range(t):

   a,b=input(‘Enter a pair: ‘).split()

   print(multiply_two_strings( a.strip() , b.strip() ))

RECOMMENDED ARTICLES





6 replies on “Multiply two strings  with example JAVA, PHP, JS, PYTHON”

  1. This is really interesting, You’re a very skilled blogger.
    I have joined your rss feed and look forward to seeking more of your excellent post.

    Also, I have shared your website in my social networks!

  2. I’m really enjoying the design and layout of your site.
    It’s a very easy on the eyes which makes it much more enjoyable
    for me to come here and visit more often. Did you hire out a designer to create your theme?
    Superb work!

Leave a Reply

Your email address will not be published.