曾彪彪的个人网站
首页
文章列表
>>
文章详情
高精加法优化
作者:
曾彪彪
日期:
2025-06-25 07:55:37
阅读(47)
分类:
Algorithm
# P1601 A+B Problem(高精) ## 题目描述 高精度加法,相当于 a+b problem,**不用考虑负数**。 ## 输入格式 分两行输入。$a,b \leq 10^{500}$。 ## 输出格式 输出只有一行,代表 $a+b$ 的值。 ## 输入输出样例 #1 ### 输入 #1 ``` 1 1 ``` ### 输出 #1 ``` 2 ``` ## 输入输出样例 #2 ### 输入 #2 ``` 1001 9099 ``` ### 输出 #2 ``` 10100 ``` ## 说明/提示 $20\%$ 的测试数据,$0\le a,b \le10^9$; $40\%$ 的测试数据,$0\le a,b \le10^{18}$。 第一次自己做的思路: ```c++ /** start time: 8:45 End time: Type: simulator Solution: - use string to simulate a+b. - just loop the short number - handle the symbol - if the two number have the same length, handle the symbol - test case: - 99999 9999 - 9999 9999 - 99999 9 - 1 1 - 0 0 - 789 98789 first submit score: 100 cause: **/ #include <bits/stdc++.h> using namespace std; string add(string a, string b) { string result = ""; if (a.size() < b.size()) { swap(a, b); } reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); int symbol = 0; for (int i = 0; i < b.size(); i++) { int v = (a[i] - '0') + (b[i] - '0') + symbol; symbol = v / 10; char data = (v % 10) + '0'; result.push_back(data); } int index = b.size(); while (symbol > 0) { if (a.size() == index) { result.push_back('0' + symbol); symbol = 0; } else { int v = (a[index] - '0') + symbol; result.push_back(v % 10 + '0'); symbol = v / 10; index++; } } while (index < a.size()) { result.push_back(a[index]); index++; } reverse(result.begin(), result.end()); return result; } int main() { // freopen("C:/Users/zengsam/Downloads/P1042_2.in", "r", stdin); string a, b; cin >> a >> b; string ans = add(a, b); cout << ans << endl; return 0; } ``` 发现有点复杂,看别人题解,优化如下: ```c++ /** start time: 8:45 End time: Type: simulator Solution: - use string to simulate a+b. - just loop the short number - handle the symbol - if the two number have the same length, handle the symbol - test case: - 99999 9999 - 9999 9999 - 99999 9 - 1 1 - 0 0 - 789 98789 first submit score: 100 cause: **/ #include <bits/stdc++.h> using namespace std; string add(string a, string b) { string result = ""; if (a.size() < b.size()) { swap(a, b); } reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); int n = a.size() - b.size(); for (int i = 0; i < n; i++) { b.push_back('0'); } int symbol = 0; for (int i = 0; i < a.size(); i++) { int v = (a[i] - '0') + (b[i] - '0') + symbol; symbol = v / 10; char data = (v % 10) + '0'; result.push_back(data); } if (symbol > 0) { result.push_back('0' + symbol); } reverse(result.begin(), result.end()); return result; } int main() { // freopen("C:/Users/zengsam/Downloads/P1042_2.in", "r", stdin); string a, b; cin >> a >> b; string ans = add(a, b); cout << ans << endl; return 0; } ```
评论(0)
评论(必填)
名称(必填)
联系方式(可选)
验证码(必填)
提交
评论(必填)
名称(必填)
联系方式(可选)
验证码(必填)