您的位置:首页 > 其它

leetcode 43. Multiply Strings

2016-09-13 21:52 417 查看
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.

Converting the input string to integer is NOT allowed.

You should NOT use internal library such as BigInteger.

输入的都是正数

输入的字符串超出了Integer

不许使用BigInteger

public String multiply(String num1, String num2) {
int[] result = new int[num1.length() + num2.length()];
if(num1.equals("0") || num2.equals("0")) return "0";
num1 = new StringBuilder(num1).reverse().toString();
num2 = new StringBuilder(num2).reverse().toString();
for(int i = 0;i < num1.length();i++){
for(int j = 0;j < num2.length();j++){
result[i+j] += (num1.charAt(i)-'0') * (num2.charAt(j)-'0') % 10;
result[i+j+1] += (num1.charAt(i)-'0') * (num2.charAt(j)-'0') / 10;
}
}
for(int i = 0;i < num1.length() + num2.length()-1;i++){
result[i+1] += result[i] / 10;
result[i] = result[i] % 10;
}
StringBuffer sb = new StringBuffer();
for(int i:result) sb.append((char)('0'+i));
if(result[num1.length() + num2.length()-1] == 0){
return new StringBuilder(sb.toString()).reverse().toString().substring(1);
}
else{
return new StringBuilder(sb.toString()).reverse().toString().substring(0);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: