Java - Multiply Strings
When multiplying two large numbers represented as strings, we can't directly convert them to integers (due to overflow). Instead, we simulate the multiplication as we do by hand.
Problem
Given two non-negative integers num1 and num2 as strings, return their product as a string.
Constraints:
You must not use BigInteger or long.
Input strings can be up to 10⁴ digits long.
Example:
Input:
num1 = "123", num2 = "456"
Output:
"56088"
Java Code
public class MultiplyStrings {
public static String multiply(String num1, String num2) {
int m = num1.length(), n = num2.length();
int[] res = new int[m + n];
// Multiply each digit
for (int i = m - 1; i >= 0; i--) {
int d1 = num1.charAt(i) - '0';
for (int j = n - 1; j >= 0; j--) {
int d2 = num2.charAt(j) - '0';
int sum = d1 * d2 + res[i + j + 1];
res[i + j + 1] = sum % 10;
res[i + j] += sum / 10;
}
}
// Convert result array to string
StringBuilder sb = new StringBuilder();
for (int num : res) {
if (sb.length() == 0 && num == 0) continue; // skip leading zeros
sb.append(num);
}
return sb.length() == 0 ? "0" : sb.toString();
}
public static void main(String[] args) {
String num1 = "123";
String num2 = "456";
System.out.println("Product: " + multiply(num1, num2)); // Output: 56088
}
}