1.题目的原意:
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
note:You must not use any built-in BigInteger library or convert the inputs to integer directly.
2.Example:
Input: num1 = "2", num2 = "3"
Output: "6"
Input: num1 = "123", num2 = "456"
Output: "56088"
3.思想:
拿到题目不要想当然的把其转换成int型,这样就失去了此题的意义了,当两个数字不是很大的时候不会溢出,当两个数字相当大的时候,就会溢出。
所以,以两个字符窜的长度和构建一个int[]型数组,两个数字相乘其结果最多为两个数字的总长度和
int[] temp = new int[num1.length() + num2.length()];
再以两个for循环将其存放至我们构建的数组内,注意遍历的时候从后往前遍历,也就是从个位数开始,有些人不习惯这种,可以将字符窜反转,从0开始遍历,皆可,个人习惯。在遍历的时候有两个细节:
a . temp[i+j+1]:此是保证数组不越界,以num1="123"和num2="456"为例,num1最大索引为2,num2亦如此,和为4,如果以此存放,就会出现数组漏存的情况
b.(num1.charAt(i)-'0') * (num2.charAt(j)-'0');将取出的字符-‘0’操作,如果不做此操作,肯定会得出一个错误的结果。
存放完数组后,在对此数组进行操作,依然是从后往前遍历,将进位以前一位进行和计算,然后在取模粗放到当前索引位置,直至结束。
最后不要忘记删除前置0,然后存入StringBuilder中,将其toString()操作后返回。return sb.toString().length() == 0 ? "0" : sb.toString();一定要判断,如果直接返回sb.toString()的话,就不严谨了,当两个数字都为"0"的时候就会返回为空了,因为在删除前置0的操作过程将其过滤掉了。所以要最后进行判断之后再返回。
总结,算法不光是要将其写出来,不仅仅效率,可读性等要考虑,细节和严谨型也不能忽视。
4.我的解法:
public String multiply(String num1, String num2) {
// "123" "456"
if(num1 == null || num1.isEmpty() || num2 == null || num2.isEmpty()) return "";
int[] temp = new int[num1.length() + num2.length()];
for(int i=num1.length()-1; i>=0; i--) {
for(int j=num2.length()-1; j>=0; j--) {
temp[i+j+1] += (num1.charAt(i)-'0') * (num2.charAt(j)-'0');
}
}
// handle the temp array
for(int i=temp.length-1; i>0; i--) {
temp[i-1] += temp[i]/10;
temp[i] %= 10;
}
// delete the leading zero
StringBuilder sb = new StringBuilder();
for(int i=0; i< temp.length; i++) {
if(sb.length() == 0 && temp[i] == 0) continue;
sb.append(temp[i]);
}
return sb.toString().length() == 0 ? "0" : sb.toString();
}