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:
1 翻转string
2 建立数组,双层循环遍历两个string,把单位的乘积累加到数组相应的位置
3 处理进位并输出
4 注意前导零的corner case
public class Solution {
public String multiply(String num1, String num2) {
//reverse the string first
String n1 = new StringBuilder(num1).reverse().toString();
String n2 = new StringBuilder(num2).reverse().toString();
//res is for storing the result of multiply
int[] res = new int[n1.length() + n2.length()];
for(int i = 0; i < n1.length(); i++) {
for(int j = 0; j < n2.length(); j++) {
//count the result at right place
res[i + j] += (n1.charAt(i) - '0') * (n2.charAt(j) - '0');
}
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < res.length; i++) {
int digit = res[i] % 10; //for current position
int carry = res[i] / 10; //for carry
if(i + 1 < res.length) {
res[i + 1] += carry;
}
sb.insert(0, digit); //prepend
}
while(sb.charAt(0) == '0' && sb.length() > 1) {
sb.deleteCharAt(0); //delete 0 at ahead
}
return sb.toString();
}
}
No comments:
Post a Comment