您的位置:首页 > 其它

leetcode-43 Multiply Strings

2015-10-10 20:44 393 查看
问题描述:

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.

 

问题分析:

问题难点在于该字符串表示的数字可能是无穷大的;

采用最基础的按十位进行逐位相乘,进位叠加的方法,需要注意相应为位坐标即可;



代码:

public class Solution {
public String multiply(String num1, String num2) {
//实现平常的乘法运算即可
int[] resnums = new int[num1.length() + num2.length()];

for(int i = num1.length() - 1; 0 <= i; i--) {
// 进位
int carry = 0;
for (int j= num2.length() - 1; 0 <= j; j--) {
resnums[i + j + 1] += ((num1.charAt(i) - '0') * (num2.charAt(j) - '0') +carry);
carry = resnums[i + j + 1] / 10;
resnums[i + j + 1] %= 10;
}
// 不要忽略了最后的进位
resnums[i] += carry;
}

StringBuffer buffer = new StringBuffer();
boolean isZero = true;
//去除零位
for(int i = 0; i < resnums.length; i++) {
if (resnums[i] == 0 && isZero)
continue;
buffer.append(resnums[i]);
isZero = false;
}
return buffer.length() > 0 ? buffer.toString() : "0";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: