top1编程
← 返回题目
题解

【基础】计算表达式

1 条题解

  • 0
    @ 2026-7-30 1:08:17

    解题思路

    先读入表达式中的数据,再按题目规定的运算顺序计算结果。

    参考代码

    // 读取题目给出的数据。
    // 按照题意完成计算。
    // 这道题的做法:先读入题目给出的数据,再用简单的循环和判断完成要求。
    #include<bits/stdc++.h>
    using namespace std;  
    int main(){           
        string s1;
        cin>>s1;
        int i,t = s1[0] - 48;
    	for(i = 1;i < s1.length();i = i + 2)
    	{
    		if(s1[i] == '+'){
    			t = t + s1[i + 1] - 48;
    		}else if(s1[i] == '-'){
    			t = t - (s1[i + 1] - 48);
    		}else if(s1[i] == '*'){
    			t = t * (s1[i + 1] - 48);
    		}
    	}
    	cout<<t<<endl;
    	return 0;
    }
    

    复杂度

    代码只使用了简单变量、循环和判断。若循环检查了 n 个数据,时间复杂度通常为 O(n);没有开辟与输入规模相关的额外数组时,空间复杂度为 O(1)。

    • 1