#leetcode#Basic Calculator

本文介绍如何实现一个基本的计算器,用于评估包含加减运算、括号和整数的简单表达式字符串。通过解析输入字符串并遵循特定规则,实现对不同操作符和括号的正确处理,最终计算得出结果。

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

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

Note: Do not use the eval built-in library function.


只有加减的计算器, 用了如下几个变量

res表示当前计算的结果,

num表示当前的数字, 比如 123 + 1 中的123就需要多个字符组合起来

sign表示当前num之前的操作符是 + 还是 -, 

‘(’ 代表需要把之前的res和左括号之前的sign 放到stack中,并且把状态清零,

‘)’ 表示需要把当前括号内的res计算出来, 出栈, res * sign就是加或者减括号内的结果 比如 1 - (1 + 2)

‘-’ 和 ‘+’ 表示当前字符已经不是digit了,所以num的计算已经结束, 可以结合之前的sign加到 res中, 然后 num要重新置零, 

然后循环结束时还要把最后的 num 加上, 考虑这个例子   (12 - 23) + 5

//  21 - (20 - 3) + 5

public class Solution {
    public int calculate(String s) {
        if(s == null || s.length() == 0)
            return 0;
        
        int num = 0;
        int res = 0;
        int sign = 1;
        LinkedList<Integer> stack = new LinkedList<Integer>();
        for(int i = 0; i < s.length(); i++){
            char c = s.charAt(i);
            
            if(Character.isDigit(c)){
                num = num * 10 + c - '0';
            }else if(c == '+'){
                res += num * sign;
                sign = 1;
                num = 0;
            }else if(c == '-'){
                res += num * sign;
                sign = -1;
                num = 0;
            }else if(c == '('){
                stack.push(res);
                stack.push(sign);
                res = 0;
                num = 0;
                sign = 1;
            }else if(c == ')'){
                res += num * sign;
                num = 0;
                sign = 1;
                res *= stack.pop();
                res += stack.pop();
            }
        }
        
        res += num * sign;
        
        return res;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值