给定两个以字符串形式表示的非负整数 num1
和 num2
,返回 num1
和 num2
的乘积,它们的乘积也表示为字符串形式。
这道题的思路就是字符串依次进行计算并存为字符串,我一开始用python写的时候是分别计算第一个数与第二个数逐位的乘积,需要每次在值后面补零确保计算正确,后来用位数之间的十进制关系改进了代码。然而这两种代码都用到了内置函数str和int直接转换大数这样就没有意义了。我觉得大数计算是为了防止数据过大占用太多内存和溢出,所以用int函数逐位计算并保存为字符串实现是必要的,当然,如果不怕麻烦也可以利用ASCII码对应的数值进行计算操作也可以。所以在C++代码里我先是逐个数计算后存入字符串,然后将所有字符串串相加,相加的过程也是逐位进行相加并及时保存到字符串,这样才是这道题真正的意义。
python:
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if num1 == "0" or num2 == "0":
return "0"
n1 = len(num1)
n2 = len(num2)
i = n1 - 1
j = n2 - 1
store = []
while i >= 0:
x1 = int(num1[i])
c = 0
temp = "0" * (n1 - i - 1)
j = n2 - 1
while j >= 0:
x2 = int(num2[j])
x = (x1 * x2 + c)
temp = str(x % 10) + temp
c = (x / 10)
if(j == 0 and c != 0):
temp = str(c) + temp
break
j -= 1
store.append(temp)
i -= 1
if len(store) == 1:
return store[0]
s = 0
for i in range(len(store)):
s += int(store[i])
return str(s)
python简化:
其实如果不考虑要求只为了实现结果可以直接简化成以下一句:
return str(int(num1) * int(num2))
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
if num1 == "0" or num2 == "0":
return "0"
sumNum = 0
for i in range(len(num1)):
x1 = int(num1[i])
y = 0
for j in range(len(num2)):
x2 = int(num2[j])
y = y * 10 + (x1 * x2)
sumNum = sumNum * 10 + y
return str(sumNum)
C++:
C++写的代码是真正意义上每一次计算无论是加还是乘都把小数值转换成字符串存储起来,所以相对较复杂,其实还可以写得更简单。
class Solution {
public:
string multiply(string num1, string num2) {
if(num1 == "0" || num2 == "0") return "0";
int i = num1.length() - 1;
vector<string> store;
while(i <= num1.length()){
int x1 = static_cast<int>(num1[i]) - 48;
int j = num2.length() - 1;
int c = 0;
string temp;
for(int k = 0;k < (num1.length() - i - 1);k++) temp += "0";
while(j <= num2.length()){
int x2 = static_cast<int>(num2[j]) - 48;
int x = x1 * x2 + c;
temp += static_cast<char>(x % 10 + 48);
c = x / 10;
if(j == 0 && c != 0) temp += static_cast<char>(c + 48);
j -= 1;
}
for(int k = temp.length();k < (num1.length()+num2.length());k++) temp += "0" ;
store.push_back(temp);
i -= 1;
}
string res;
int c = 0;
int n = store[0].length();
for(int i = 0;i < n;i++){
int s = 0;
for(int j = 0;j < store.size();j++){
s += (static_cast<int>(store[j][i]) - 48);
}
s += c;
c = s / 10;
res = static_cast<char>(s % 10 + 48) + res;
if(i == (n - 1) && c != 0) res = static_cast<char>(c + 48) + res;
}
if(res[0] == '0'){
res.erase(res.begin(),res.begin()+1);
}
return res;
}
};