您的位置:首页 > 其它

leetcode -- Multiply Strings

2013-08-05 23:02 381 查看
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.

大整数乘法,一位一位往上乘,注意进位的处理即可。此外,注意0的处理

public class Solution {
public String multiply(String num1, String num2) {
// Start typing your Java solution below
// DO NOT write main() function
int l1 = num1.length();
int l2 = num2.length();

int[] num = new int[l1 + l2 + 1];
for(int i = 0; i <= l2 - 1; i ++){
int carry = 0;
int a = num2.charAt(l2 - 1 - i) - '0';
for(int j = 0; j <= l1 - 1; j ++){
int b = num1.charAt(l1 - 1 - j) - '0';
num[i + j] += a * b + carry;
carry = num[i + j] / 10;
num[i + j] = num[i + j] % 10;
}
num[i + l1] = carry;
}

int i = num.length - 1;
while(i > 0 && num[i] == 0){
i--;
}

StringBuilder sb = new StringBuilder();
while(i >= 0){
sb.append(num[i--]);
}
return sb.toString();
}
}


ref:http://gongxuns.blogspot.com/2013/01/leetcode-multiply-strings.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: