两个用字符串表示的数字相加,不转换为int或者long型计算
思路
从后往前计算,按照竖式的思路,用一个变量存储进位。
如果一个字符串为空就用0表示。
题目
- 二进制求和
class Solution {
public:
string addBinary(string a, string b) {
int i = a.size() - 1, j = b.size() - 1;
int carry = 0;
string res;
while(i >= 0 || j >= 0){
int x = i >= 0? a[i] - '0' : 0;
int y = j >= 0? b[j] - '0' : 0;
int temp = x + y + carry;
res = to_string(temp % 2) + res;
carry = temp / 2;
i--;j--;
}
if(carry){
res = '1' + res;
}
return res;
}
};
- 字符串相加
class Solution {
public:
string addStrings(string num1, string num2) {
int n1 = num1.size();
int n2 = num2.size();
int carry = 0;
string res;
while (n1 >= 0 || n2 >= 0 || carry != 0) {
int x = n1 >= 0? num1[n1] - '0' : 0;
int y = n2 >= 0? num2[n2] - '0' : 0;
int cur = (x + y + carry) % 10;
res = res + to_string(cur);
carry = (x + y + carry) / 10;
n1--;
n2--;
}
return res;
}
};
- 字符串相乘
先乘后加,乘法后面要添0
class Solution {
public:
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0") {
return "0";
}
string ans = "0";
int m = num1.size(), n = num2.size();
for (int i = n - 1; i >= 0; i--) {
string curr;
int add = 0;
for (int j = n - 1; j > i; j--) {
curr.push_back(0);
}
int y = num2.at(i) - '0';
for (int j = m - 1; j >= 0; j--) {
int x = num1.at(j) - '0';
int product = x * y + add;
curr.push_back(product % 10);
add = product / 10;
}
while (add != 0) {
curr.push_back(add % 10);
add /= 10;
}
reverse(curr.begin(), curr.end());
for (auto &c : curr) {
c += '0';
}
ans = addStrings(ans, curr);
}
return ans;
}
string addStrings(string &num1, string &num2) {
int i = num1.size() - 1, j = num2.size() - 1, add = 0;
string ans;
while (i >= 0 || j >= 0 || add != 0) {
int x = i >= 0 ? num1.at(i) - '0' : 0;
int y = j >= 0 ? num2.at(j) - '0' : 0;
int result = x + y + add;
ans.push_back(result % 10);
add = result / 10;
i--;
j--;
}
reverse(ans.begin(), ans.end());
for (auto &c: ans) {
c += '0';
}
return ans;
}
};
作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/multiply-strings/solution/zi-fu-chuan-xiang-cheng-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
用数组存储字符串的结果简化过程
class Solution {
public:
string multiply(string num1, string num2) {
if(num1 == "0" || num2 == "0") return "0";
int m = num1.size(), n = num2.size();
//不是卷积就是从后面相乘
vector<int> res(m + n);
for(int i = m - 1; i >= 0; i--){
int x = num1[i] - '0';
for(int j = n - 1; j >= 0; j--){
int y = num2[j] - '0';
res[i + j + 1] += x * y;
}
}
for(int i = m + n - 1; i > 0; i--){
res[i - 1] += res[i] / 10;
res[i] = res[i] % 10;
}
int index = res[0] == 0? 1 : 0;
string ans;
while(index < m + n){
ans += (res[index] + '0');
index++;
}
return ans;
}
};