welcome to my blog
LeetCode Top Interview Questions 43. Multiply Strings (Java版; Medium)
题目描述
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contain only digits 0-9.
Both num1 and num2 do not contain any leading zero, except the number 0 itself.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
第一次做; 核心: 两个因数和积的对应关系; 最优解中跳过最高位的0还是很巧妙的; 变量命名方式不好, 看看最优解的!
/*
数值运算和String挂钩, 往往是需要考虑溢出问题, 也就是大数问题
关键是要弄明白乘法的计算步骤
核心: 乘数的索引和结果的索引之间的对应关系
*/
class Solution {
public String multiply(String num1, String num2) {
if(num1.equals("0") || num2.equals("0"))
return "0";
int[] res = new int[num1.length()+num2.length()];
int cur = 0;
for(int i=num1.length()-1; i>=0; i--){
for(int j=num2.length()-1; j>=0; j--){
int tmp = (num1.charAt(i)-'0') * (num2.charAt(j)-'0') + res[i+j+1];
res[i+j+1] = tmp%10;
res[i+j] = tmp/10 + res[i+j];
}
}
StringBuilder sb = new StringBuilder();
int i = 0;
//去掉最高位的0
if(res[0]==0)
i++;
for(; i<res.length; i++){
sb.append(res[i]);
}
return sb.toString();
}
}
LeetCode最优解 探寻乘法竖式的规律, 关键: 索引的对应关系, 下面这张图, 索引反过来也行, 之所以逆着来,是因为得到的结果正好是由高位到低位, 比如说25*13的结果放在数组中是[0,3,2,5], 和平时的写法习惯一样
Remember how we do multiplication?
Start from right to left, perform multiplication on every pair of digits, and add them together. Let's draw the process! From the following draft, we can immediately conclude:
`num1[i] * num2[j]` will be placed at indices `[i + j`, `i + j + 1]`
public String multiply(String num1, String num2) {
int m = num1.length(), n = num2.length();
int[] pos = new int[m + n];
for(int i = m - 1; i >= 0; i--) {
for(int j = n - 1; j >= 0; j--) {
int mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
int p1 = i + j, p2 = i + j + 1;
int sum = mul + pos[p2];
pos[p1] += sum / 10;
pos[p2] = (sum) % 10;
}
}
StringBuilder sb = new StringBuilder();
for(int p : pos)
//很巧妙的去掉了最高位的0
if(!(sb.length() == 0 && p == 0))
sb.append(p);
return sb.length() == 0 ? "0" : sb.toString();
}