-
Notifications
You must be signed in to change notification settings - Fork 385
Closed
Description
LeetCode Username
Komal145-web
Problem Number, Title, and Link
- Multiply Strings https://leetcode.com/problems/multiply-strings/description/
Bug Category
Problem description, Problem examples, Problem constraints
Bug Description
43. Multiply Strings
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Constraints:
1 <= num1.length, num2.length <= 200
num1 and num2 consist of digits only.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
Language Used for Code
Java
Code used for Submit/Run operation
class Solution {
public String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) return "0";
int m = num1.length();
int n = num2.length();
int[] res = new int[m + n];
for (int i = m - 1; i >= 0; i--) {
for (int j = n - 1; j >= 0; j--) {
int digit1 = num1.charAt(i) - '0';
int digit2 = num2.charAt(j) - '0';
int product = digit1 * digit2;
int posLow = i + j + 1;
int posHigh = i + j;
product += res[posLow]; // add existing carry
res[posLow] = product % 10;
res[posHigh] += product / 10;
}
}
// Convert to string, skip leading zero
StringBuilder sb = new StringBuilder();
for (int num : res) {
if (!(sb.length() == 0 && num == 0)) {
sb.append(num);
}
}
return sb.toString();
}
}Expected behavior
solved
Screenshots
Additional context
No response
Metadata
Metadata
Assignees
Labels
No labels