力扣题-1.3
[力扣刷题攻略] Re:从零开始的力扣刷题生活
力扣题1:43. 字符串相乘
解题思想:类似计算时采用的竖式乘法。首先取得num2的低位,并补齐对应的0,然后与num1进行相乘,然后进行字符串的相加操作。
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
## 如果其中有个为0,则相乘后得0
if num1 == "0" or num2 == "0":
return "0"
## 定义ans作为最后的返回值
ans = "0"
m = len(num1)
n = len(num2)
## 从低位开始遍历num2,用一位与num1进行乘法
for i in range(n-1,-1,-1):
add = 0
y = int(num2[i])
curr = ['0']*(n-1-i)
## 与num1进行乘法操作
for j in range(m-1,-1,-1):
x = int(num1[j])
temp = x*y+add
curr.append(str(temp%10))
add = temp // 10
if add > 0:
curr.append(str(add))
## 因为是通过append添加的最后需要进行翻转
curr = "".join(curr[::-1])
## 字符串的加法操作
ans = self.addStrings(ans,curr)
return ans
def addStrings(self, num1, num2):
## 进行字符串的加法操作,从低位开始相加
i, j = len(num1) - 1, len(num2) - 1
add = 0
ans = list()
while i >= 0 or j >= 0 or add != 0:
x = int(num1[i]) if i >= 0 else 0
y = int(num2[j]) if j >= 0 else 0
result = x + y + add
ans.append(str(result % 10))
add = result // 10
i -= 1
j -= 1
## 最后需要进行翻转
return "".join(ans[::-1])
class Solution {
public:
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0") {
return "0";
}
string ans = "0";
int m = num1.length();
int n = num2.length();
for (int i = n - 1; i >= 0; i--) {
int add = 0;
int y = num2[i] - '0';
string curr(n - 1 - i, '0');
for (int j = m - 1; j >= 0; j--) {
int x = num1[j] - '0';
int temp = x * y + add;
curr.push_back(temp % 10 + '0');
add = temp / 10;
}
if (add > 0) {
curr.push_back(add + '0');
}
reverse(curr.begin(), curr.end());
ans = addStrings(ans, curr);
}
return ans;
}
string addStrings(string num1, string num2) {
int i = num1.length() - 1;
int j = num2.length() - 1;
int add = 0;
string result;
while (i >= 0 || j >= 0 || add != 0) {
int x = (i >= 0) ? num1[i] - '0' : 0;
int y = (j >= 0) ? num2[j] - '0' : 0;
int sum = x + y + add;
result.push_back(sum % 10 + '0');
add = sum / 10;
i--;
j--;
}
reverse(result.begin(), result.end());
return result;
}
};