Multiply Strings LeetCode Solution

Here, We see Multiply Strings problem Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.

Multiply Strings LeetCode Solution

Multiply Strings LeetCode Solution

Problem Statement ->

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.

Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"

Multiply Strings Leetcode Solution C++ ->

class Solution { public: string multiply(string num1, string num2) { if(num1=="0"||num2=="0"){return "0";} int n = num1.length(),m = num2.length(); string ans(n+m,'0'); for(int i=n-1;i>=0;i--){ for(int j=m-1;j>=0;j--){ int num = (num1[i] - '0') * (num2[j] - '0') + ans[i+j+1] - '0'; ans[i+j+1] = num%10 + '0'; ans[i+j] += num/10; } } for(int i=0;i<ans.length();i++){ if(ans[i] != '0'){ return ans.substr(i);} } return "0"; } };
Code language: C++ (cpp)

Multiply Strings Leetcode Solution Java ->

class Solution { public String multiply(String num1, String num2) { int m = num1.length(), n = num2.length(); int[] pos = new int[m + n]; for(int i = m - 1; i >= 0; i--) { for(int j = n - 1; j >= 0; j--) { int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0'); int p1 = i + j, p2 = i + j + 1; int sum = mul + pos[p2]; pos[p1] += sum / 10; pos[p2] = (sum) % 10; } } StringBuilder sb = new StringBuilder(); for(int p : pos) if(!(sb.length() == 0 && p == 0)) sb.append(p); return sb.length() == 0 ? "0" : sb.toString(); } }
Code language: Java (java)

Multiply Strings Leetcode Solution Python ->

class Solution(object): def multiply(self, num1, num2): return str(self.strint(num1)*self.strint(num2)) def strint(self,n): result=0 for i in range(len(n)): result = result*10 + ord(n[i])-ord('0') return result
Code language: Python (python)