Basic Calculator II(Leetcode)

本文介绍了一个简单的计算器实现方法,该计算器能处理包含加减乘除运算的正数表达式。通过遍历字符串并利用栈来存储中间结果,最终计算出表达式的值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +-*/ operators and empty spaces . The integer division should truncate toward zero.

Example 1:

Input: "3+2*2"
Output: 7

Example 2:

Input: " 3/2 "
Output: 1

Example 3:

Input: " 3+5 / 2 "
Output: 5

Note:

  • You may assume that the given expression is always valid.
  • Do not use the eval built-in library function.

实现一个计算器,可以进行正数的加减乘除运算.

思路:和上一题的思路类似,遍历所有字符,得到数字,针对不同的运算符进行不同的操作。借助stack存储所有中间结果,最后依次运算。

class Solution {
public:
	int calculate(string s) {
		int res = 0, num = 0, n = s.size();
		char op = '+';//第一个数永远是整数
		stack<int> st;
		for (int i = 0; i < n; i++) {
			if (isdigit(s[i])) {
				num = num * 10 + s[i]-'0';//得到数字
			}
			if ((s[i] < '0' && s[i] != ' ') || (i==n-1)) {//最后一个数要进入运算
				if (op == '+') {
					st.push(num);
				}
				if (op == '-') {
					st.push(-num);
				}
				if (op == '*') {
					int tmp = st.top()*num;
					st.pop();//弹出第一个数
					st.push(tmp);
				}
				if (op == '/') {
					int tmp = st.top()/num;
					st.pop();
					st.push(tmp);
				}
				op = s[i];
				num = 0;
			}
		}
		while (!st.empty()) {
			res += st.top();
			st.pop();
		}
		return res;
	}
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值