题目:
?
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.
题意:
给定两个数字分别用字符串表示出来,返回这两个数字的乘积,同样用字符串表示。
注意:数字会非常大而且是非负的。
算法分析:
方法一:
直接乘会溢出,这里可以利用java中的 BigInteger
方法二:
参考http://pisxw.com/algorithm/Multiply-Strings.html
该题需要知道,m和n位数的乘积,最终结果为m+n-1位或是m+n位(进位时)。乘法计算中可以发现,结果中第i位,应该由第一个字符串中的第1位乘以第二个字符串中的第i位,第一个字符串中的第2位乘以第二个字符串中的第i-1位,.......第一个字符串中的第i位乘以第二个字符串中的第1位,最后累加求得,最后我们取个位上的数值,然后剩下的作为进位放到下一轮循环中
AC代码:
方法一:
?
import java.math.BigInteger; //Java
public class Solution
{
public String multiply(String num1, String num2)
{
BigInteger temp1 = new BigInteger(num1);
BigInteger temp2 = new BigInteger(num2);
BigInteger result = temp1.multiply(temp2);
return result.toString();
}
}
方法二:
?
?
public class Solution
{
public String multiply(String num1, String num2)
{
if(num1==null || num2==null)
return ;
if(num1.charAt(0)=='0')
return 0;
if(num2.charAt(0)=='0')
return 0;
int num1length=num1.length();
int num2length=num2.length();
//分别对两个开始字符串进行转置,便于后面的下标遍历
num1=new StringBuilder(num1).reverse().toString();
num2=new StringBuilder(num2).reverse().toString();
StringBuilder res=new StringBuilder();
int jinwei=0;
//从低位开始计算,最后乘积的位数为m+n-1,如果进位则是m+n
for(int i=0;i
?
?
?