http://oj.leetcode.com/problems/multiply-strings/
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 String multiply(String num1, String num2)
问题分析:嗯,我们可以用到Integer.parseInt(),把两个字符串变成整型数,然后相乘返回结果。你相信这题可以这么做吗?呵呵....:-)
这题本质就是一个大数相乘。给出的Note就说这个数字可以特别大。这题并不是特别难,你小学的时候乘法竖式怎么做这里就怎么做。一位一位的乘,然后结果相加。所以我做了两个helper函数,一个是大数相加,另一个是一个数乘以一个个位数。给出代码如下:
public String multiplysinglebit(String num1, int singlebit,int bitno){//这个bitno其实就表示十进制你后面屁股跟多少个0。
StringBuilder res = new StringBuilder();
int next = 0;
for(int i = num1.length() - 1; i >= 0; i--){
int curbit = num1.charAt(i) - '0';
curbit = curbit * singlebit + next;
next = curbit / 10;
curbit %= 10;
res.append(curbit + "");
}
if(next != 0)
res.append(next + "");
res.reverse();//
for(int i = 0; i < bitno; i++)
res.append("0");
return res.toString();
}
public String addString(String num1, String num2){
StringBuilder res = new StringBuilder();
int next = 0, curbit = 0;
for(int i = num1.length() - 1, j = num2.length() - 1; i >= 0 || j >= 0; i--, j--){
curbit = 0;
if(i >= 0){
curbit += num1.charAt(i) - '0';
}
if(j >= 0){
curbit += num2.charAt(j) - '0';
}
curbit += next;
next = curbit > 9 ? 1 : 0;
curbit %= 10;
res.append(curbit + "");
}
if(next != 0)
res.append(next + "");
res.reverse();
return res.toString();
}
public String multiply(String num1, String num2) {
String res = "0";
if(num1.equals("0") || num2.equals("0"))
return res;
for(int i = num2.length() - 1; i >= 0; i--){
String curres = multiplysinglebit(num1, num2.charAt(i) -'0', num2.length() - 1 - i);
res = addString(res, curres);
}
return res;
}
本文介绍了一种解决两个大数相乘问题的算法实现,通过字符串表示的大数使用类似于小学数学乘法的方式进行逐位相乘并累加,最终得到结果。文中提供了详细的Java代码实现,包括单个数位相乘和两个大数相加的辅助函数。
384

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



