public class MultiplyStrings {
public static void main(String[] args) {
String num1 = "123", num2 = "456";
System.out.println(multiply(num1, num2));
}
private static String multiply(String num1, String num2) {
if (num1.equals("0") || num2.equals("0")) {
return "0";
}
StringBuilder firstNum = new StringBuilder(num1);
StringBuilder secondNum = new StringBuilder(num2);
firstNum.reverse();
secondNum.reverse();
int N = firstNum.length() + secondNum.length();
StringBuilder answer = new StringBuilder();
for (int i = 0; i < N; i++) {
answer.append("0");
}
int digit1, digit2;
for (int place2 = 0; place2 < secondNum.length(); place2++) {
digit2 = secondNum.charAt(place2) - '0';
for (int place1 = 0; place1 < firstNum.length(); place1++) {
digit1 = firstNum.charAt(place1) - '0';
int currentPos = place1 + place2;
int carry = answer.charAt(currentPos) - '0';
int product = digit1 * digit2 + carry;
answer.setCharAt(currentPos, (char) (product % 10 + '0'));
int value = (answer.charAt(currentPos + 1) - '0') +
product / 10;
answer.setCharAt(currentPos + 1, (char) (value + '0'));
}
}
if (answer.charAt(answer.length() - 1) == '0') {
answer.deleteCharAt(answer.length() - 1);
}
answer.reverse();
return answer.toString();
}
}