Multiply Strings
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:
参考自http://blog.csdn.net/fightforyourdream/article/details/17370495
相当优雅的算法,主页君稍微改进,把翻转String这一步拿掉了。比起一般的做法,这个算法很容易就BUG FREE.
思路:
1 建立数组,双层循环遍历两个string,把单位的乘积累加到数组相应的位置
2 处理进位并输出
3 注意前导零的corner case
public class Solution {
public String multiply(String num1, String num2) {
if (num1 == null || num2 == null) {
return null;
} int len1 = num1.length();
int len2 = num2.length(); int[] product = new int[len1 + len2]; // 计算相应位置的product.
for (int i = 0; i < len1; i++) {
for (int j = 0; j < len2; j++) {
// 注意,这里要使用+=以不断累加乘积
product[i + j] += (num1.charAt(len1 - 1 - i) - '0') * (num2.charAt(len2 - 1 - j) - '0');
}
} StringBuilder ret = new StringBuilder(); int carry = 0;
// 计算进位
for (int i = 0; i < len1 + len2; i++) {
product[i] = product[i] + carry;
int digit = product[i] % 10;
carry = product[i] / 10;
ret.insert(0, digit);
} // 去掉前导0
while (ret.length() > 1 && ret.charAt(0) == '0') {
ret.deleteCharAt(0);
} return ret.toString();
}
}
2015.1.20 redo
public String multiply(String num1, String num2) {
// 18:24
if (num1 == null || num2 == null) {
return null;
} int len1 = num1.length();
int len2 = num2.length();
int[] sum = new int[len1 + len2]; // sum all of the mutiply result.
for (int i = ; i < len1; i++) {
for (int j = ; j < len2; j++) {
sum[i + j] += (num1.charAt(len1 - - i) - '') * (num2.charAt(len2 - - j) - '');
}
} int carry = ;
for (int i = ; i < len1 + len2; i++) {
sum[i] = sum[i] + carry; // Bug1: this line should be processed first.
carry = sum[i] / ;
sum[i] %= ;
} StringBuilder sb = new StringBuilder();
for (int i = ; i < len1 + len2; i++) {
sb.insert(, sum[i] + "");
} // delete the leading "0"
while (sb.charAt() == '' && sb.length() != ) {
sb.deleteCharAt();
} return sb.toString();
}
请至主页群GITHUB:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/Multiply.java