top1编程
← 返回题目
题解

【入门】简单a+b

1 条题解

  • 0
    @ 2026-7-31 4:55:38

    解题思路

    题目要求计算 a+b= 格式的加法表达式。

    比如 1+2= 的结果是 3,23+58= 的结果是 81。

    方法:

    1. 找到 + 的位置,把字符串分成左右两段
    2. 右边段末尾有 = 号,去掉
    3. 把两段转成整数相加

    参考代码

    #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