Problem:
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.
大数乘法,通常采用的是模拟手工计算的方法,时间复杂度为O(n^2)。网上找了一下,时间复杂度更低一些的方法有分治法和FFT算法,但实现较为复杂。
Solution:
public class Solution {
public String multiply(String num1, String num2) {
if(num1==null||num2==null)
return null;
int tmp = 0;
StringBuilder res = new StringBuilder();
for(int i=0;i<num1.length()+num2.length();i++)
res.append('0');
for(int i=num1.length()-1;i>=0;i--)
for(int j=num2.length()-1;j>=0;j--)
{
tmp = (num1.charAt(i)-'0')*(num2.charAt(j)-'0');
int k = 1;
do {
tmp += res.charAt(i+j+k)-'0';
res.setCharAt(i+j+k, Integer.toString(tmp%10).charAt(0));
k--;
} while ((tmp/=10)>0);
}
while(res.length()>1&&res.charAt(0)=='0')
res.deleteCharAt(0);
return res.toString();
}
}
public String multiply(String num1, String num2) {
if(num1==null||num2==null)
return null;
int tmp = 0;
StringBuilder res = new StringBuilder();
for(int i=0;i<num1.length()+num2.length();i++)
res.append('0');
for(int i=num1.length()-1;i>=0;i--)
for(int j=num2.length()-1;j>=0;j--)
{
tmp = (num1.charAt(i)-'0')*(num2.charAt(j)-'0');
int k = 1;
do {
tmp += res.charAt(i+j+k)-'0';
res.setCharAt(i+j+k, Integer.toString(tmp%10).charAt(0));
k--;
} while ((tmp/=10)>0);
}
while(res.length()>1&&res.charAt(0)=='0')
res.deleteCharAt(0);
return res.toString();
}
}
本文介绍了一种通过字符串模拟手工计算实现大数乘法的方法,适用于任意大小的非负整数相乘,并提供了详细的Java代码实现。

被折叠的 条评论
为什么被折叠?



