1.高精度加法
https://leetcode-cn.com/problems/add-strings/
https://leetcode-cn.com/problems/additive-number/
https://leetcode-cn.com/problems/plus-one/
https://leetcode-cn.com/problems/add-binary/submissions/
法一:板子
class Solution {
public:
string addBinary(string a, string b) {
vector<int>A,B,C;
for(int i=a.size()-1;i>=0;i--) A.push_back(a[i]-'0');
for(int i=b.size()-1;i>=0;i--) B.push_back(b[i]-'0');
int t=0;
for(int i=0;i<A.size()||i<B.size();i++)
{
if(i<A.size()) t+=A[i];
if(i<B.size()) t+=B[i];
C.push_back(t%2);
t/=2;
}
if(t) C.push_back(1);
string c;
for(int i=C.size()-1;i>=0;i--) c+=to_string(C[i]);
return c;
}
};
法二:简化板子
class Solution {
public:
string addBinary(string a, string b) {
reverse(a.begin(),a.end());
reverse(b.begin(),b.end());
int t=0;
string c;
for(int i=0;i<a.size()||i<b.size()||t;i++)
{
if(i<a.size()) t+=a[i]-'0';
if(i<b.size()) t+=b[i]-'0';
c+=to_string(t%2);
t/=2;
}
reverse(c.begin(),c.end());
return c;
}
};
2.高进度乘法
https://leetcode-cn.com/problems/multiply-strings/
code
class Solution {
public:
string multiply(string num1, string num2) {
vector<int> A, B;
int n = num1.size(), m = num2.size();
for (int i = n - 1; i >= 0; i -- ) A.push_back(num1[i] - '0');
for (int i = m - 1; i >= 0; i -- ) B.push_back(num2[i] - '0');
vector<int> C(n + m);
for (int i = 0; i < n; i ++ )
for (int j = 0; j < m; j ++ )
C[i + j] += A[i] * B[j];
for (int i = 0, t = 0; i < C.size(); i ++ ) {
t += C[i];
C[i] = t % 10;
t /= 10;
}
int k = C.size() - 1;
while (k > 0 && !C[k]) k -- ;
string res;
while (k >= 0) res += C[k -- ] + '0';
return res;
}
};