Question:
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.
» Solve this problem
分析:
将两个数字的字符串reverse自不必说,和其他加法的算法类似,重点在于进位和当前位数。
而这道题首先建立一个长度为num1与num2之和的array,两个嵌套指针分别遍历num1,num2,每层循环中,求出两个当前位数的乘积并与array的当前位数(array[i+j])相加。这个数对10取余,就是当前的位数的当前值;这个数加上上一位(i+j+1)的值除以10,就是上一位的当前值,即,进位。
Code:
public class Solution {
public String multiply(String num1, String num2) {
// Start typing your Java solution below
// DO NOT write main() function
num1 = reverse(num1);
num2 = reverse(num2);
int[] res = new int[num1.length()+num2.length()];
for(int i=0; i<num1.length(); i++)
for(int j=0; j<num2.length(); j++){
int tmp = (num1.charAt(i)-'0')*(num2.charAt(j)-'0') + res[i+j];
res[i+j+1] = res[i+j+1] + tmp/10;
res[i+j] = tmp%10;
}
int index = 0;
for(int i=res.length-1; i>=0; i--)
if(res[i] != 0){
index = i;
break;
}
String s = "";
for(int i=index; i>=0; i--)
s += res[i];
return s;
}
private String reverse(String str){
String s = "";
for(int i=str.length()-1; i>=0; i--)
s += str.charAt(i);
return s;
}
}
总结:
相当经典的算法,和加法的如何进位、如何保留当前位有相似之处,可以拿来借鉴。