题解
【入门】简单a+b
2 条题解
-
0
1. 解题思路
找到加号,把表达式分成两个整数的字符串。去掉右半段末尾的等号,将两段转换为整数相加,输出结果。
2. 坑点和注意事项
右半段从加号之后开始,等号不是数字,要先去掉。每个数在0到999999999之间,两数和至多1999999998,原int足够。只按题目给定的a+b=格式处理,不额外解释其他运算符。
3. 复杂度
- 时间复杂度:O(L),L为表达式长度,查找、截取和转换均为线性处理。
- 空间复杂度:O(L),保存原表达式及左右两个子串;即使不计输入字符串,子串复制也需要O(L)空间。
#include <iostream> #include <string> #include <cstdlib> using namespace std; int main() { string s; cin >> s; // 找到 + 的位置 int pos = s.find('+'); // 左边是加号前的数字 string left = s.substr(0, pos); // 右边是加号后、等号前的数字 string right = s.substr(pos + 1); // 去掉末尾的等号 if (right.back() == '=') { right.pop_back(); } int a = atoi(left.c_str()); int b = atoi(right.c_str()); cout << a + b << endl; return 0; } -
0
解题思路
题目要求计算 a+b= 格式的加法表达式。
比如 1+2= 的结果是 3,23+58= 的结果是 81。
方法:
- 找到 + 的位置,把字符串分成左右两段
- 右边段末尾有 = 号,去掉
- 把两段转成整数相加
参考代码
#include <iostream> #include <string> #include <cstdlib> using namespace std; int main() { string s; cin >> s; int pos = s.find('+'); string left = s.substr(0, pos); string right = s.substr(pos + 1); if (right.back() == '=') { right.pop_back(); } int a = atoi(left.c_str()); int b = atoi(right.c_str()); cout << a + b << endl; return 0; }复杂度分析
- 时间复杂度:O(N)
- 空间复杂度:O(1)
- 1