题目地址
https://leetcode-cn.com/problems/multiply-strings/
题目描述
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.
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Constraints:
- 1 <= num1.length, num2.length <= 200
- num1 and num2 consist of digits only.
- Both num1 and num2 do not contain any leading zero, except the number 0 itself.
思路
题目说了不让用BigInterger等类把字符串直接转为整数。
然后呢,数字字符串的长度足足有110。
那就老老实实模拟乘法吧。
步骤:
- 模拟每位乘法,记录每个位的数字,先不管进位
- 处理每个进位
详见代码注释~~
题解
class Solution {
public String multiply(String num1, String num2) {
int len1 = num1.length();
int len2 = num2.length();
//如果有从乘数为0返回0
if(len1==1&&num1.charAt(0)=='0') return "0";
if(len2==1&&num2.charAt(0)=='0') return "0";
int[] res_i = new int[500];
String res_s = "";
//下面这个循环计算每个位上的结果(没进位)
for(int i=0;i<len1;i++)
for(int j=0;j<len2;j++){
res_i[i+j] += (num1.charAt(len1-i-1)-'0')*(num2.charAt(len2-j-1)-'0');
}
//处理进位
for(int i=0;i<len1+len2;++i) {
if(res_i[i]>=10){
res_i[i+1]+=res_i[i]/10;
res_i[i] = res_i[i]%10;
}
}
//len1位的数和len2位的数相乘的结果可能为len1+len2位或len1+len2-1位,这里做个判断
int los=0;
if(res_i[len1+len2-1]==0) los = 1;
//将保存在数组中的结果转为字符串
for(int i=0;i<len1+len2-los;++i) {
res_s = res_i[i] + res_s;
}
return res_s;
}
}