本文主要是介绍1074 宇宙无敌加法器(测试点5),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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;
}
这篇关于1074 宇宙无敌加法器(测试点5)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!