您的位置:首页 > 其它

[LeetCode] Multiply Strings 字符串相乘

2017-06-19 19:17 399 查看
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.0 后来发现事实上就依照小学学的乘法运算来即可了。



最重要的一点就是,n长度的数乘以m长度的数,那么乘积肯定是n+m或者n+m-1的长度

比方 123*100=12300 (n+m-1) 500*900=450000 (n+m)

第二点:小学乘法计算法则



你是不是发现,申明一个n+m的数组num,来存中间变量,从上加到下。

中间用一个carry来保存进位是多少,就能够算出来最后的结果??

没有做出来这个题惭愧的你稍微思考,列出了例如以下公式:

乘积=乘数1的第i位 * 乘数的第j位+ 进位carry+ 数组当前位

进位=乘积/10

数组当前位终于=乘积%10

通过两个for循环。不断刷新终于的num数组。所有结束后最后得到了值。

最后将进位可能为0的第一个数组忽略。剩下的转换为字符串返回。

(当然没有想出来也正常。



多推敲推敲。最恨这样的题)

public String multiply(String num1, String num2) {
if(num1.equals("0") || num2.equals("0")) return "0";
int len1=num1.length();
int len2=num2.length();
int product,carry,i,j;
int[] num= new int[len1+len2];
for(i=len1-1;i>=0;i--){
carry=0;
for(j=len2-1;j>=0;j--){
product=carry+ (int)(num1.charAt(i)-'0')*(int)(num2.charAt(j)-'0')+num[i+j+1];
num[i+j+1]=product%10;
carry=product/10;
}
num[i+j+1]=carry;
}
i=0;
while(i<len1+len2 && num[i]==0){
i++;
}
StringBuilder sb=new StringBuilder();
while(i<len1+len2){
sb.append(num[i]);
i++;
}

return sb.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: