solution
- 每位权值不同的高精度加法
- 测试点5:结果为0的情况
#include<iostream>
#include<string>
using namespace std;
int main(){
string rule, a, b, ans = "";
int carry = 0, temp, cnt, power;
cin >> rule >> a >> b;
for(int i = a.size() - 1, j = b.size() - 1, cnt = rule.size() - 1; i >= 0 || j >= 0; i--, j--, cnt--){
if(i < 0) temp = b[j] - '0' + carry;
else if(j < 0) temp = a[i] - '0' + carry;
else temp = (a[i] - '0') + (b[j] - '0') + carry;
if(rule[cnt] == '0') power = 10;
else power = rule[cnt] - '0';
ans = to_string(temp % power) + ans;
carry = temp / power;
}
if(carry) ans = to_string(carry) + ans;
while(ans[0] == '0') ans.erase(0, 1);
if(ans.size() == 0) cout << 0;
else cout << ans;
return 0;
}
or
#include<iostream>
#include<string>
using namespace std;
int main(){
string rule, a, b, ans = "";
int carry = 0, temp, cnt, power;
cin >> rule >> a >> b;
while(a.size() < b.size()) a = "0" + a;
while(b.size() < a.size()) b = "0" + b;
for(int i = a.size() - 1; i >= 0; i--){
temp = (a[i] - '0') + (b[i] - '0') + carry;
if(rule[i] == '0') power = 10;
else power = rule[i] - '0';
ans = to_string(temp % power) + ans;
carry = temp / power;
}
if(carry) ans = to_string(carry) + ans;
while(ans[0] == '0') ans.erase(0, 1);
if(ans.size() == 0) cout << 0;
else cout << ans;
return 0;
}