标签:
Problem:
Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
Solution:
multiply each bit of string 1 with string2. Be careful of the carryIn and the position.
Code:
public class Solution {
public String multiply(String num1, String num2) {
if ( num1 == null || num2 == null) return "";
int[] result = new int[num1.length() + num2.length()];
int carryIn = 0;
for (int i = num1.length() - 1; i >= 0; i--) {
carryIn = 0;
for (int j = num2.length() - 1; j >= 0; j--) {
int a = num1.charAt(i) - '0';
int b = num2.charAt(j) - '0';
int tmp = a * b + carryIn + result[num1.length() - 1 + num2.length() - 1 - i - j];
carryIn = tmp / 10;
result[num1.length() - 1 + num2.length() - 1 - i - j] = tmp % 10;
}
result[num1.length() - 1 + num2.length() - 1 - i + 1] = carryIn;
}
// result[num1.length() + num2.length() - 1] = carryIn;
int i = num1.length() + num2.length() - 1;
while (i >= 1 && result[i] == 0) {
i--;
}
String s = "";
for (int j = i; j >= 0; j--) {
s = s + result[j];
}
return s;
}
}标签:
原文地址:http://blog.csdn.net/luckyseven7777/article/details/43907187