Last updated on October 10th, 2024 at 02:11 am
Here, We see Multiply Strings LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc., with different approaches.
List of all LeetCode Solution
Topics
Math, String
Companies
Facebook, Twitter
Level of Question
Medium
Multiply Strings LeetCode Solution
Table of Contents
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"
1. 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"; } };
2. 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(); } }
3. Multiply Strings Leetcode Solution Javascript
var multiply = function(num1, num2) { let b = BigInt(num1) * BigInt(num2) return String(b) };
4. 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