leetcode 224 basic calculator简单计算器

首先,简单计算器中就只有加法和减法,左括号右括号数字,也有可能有空格

然后,网上大神的代码是

public class Solution {
    // "1 + 1"
    public int calculate(String s) {
        if(s==null || s.length() == 0) return 0;
        
        Stack<Integer> stack = new Stack<Integer>();
        int res = 0;
        int sign = 1;
        for(int i=0; i<s.length(); i++) {
            char c = s.charAt(i);
            if(Character.isDigit(c)) {
                int cur = c-'0';
                 //当下一个字符也是数字(意思就是不是一个只有0-9的数字,可能12 34 等)
                 //,并且不越界
                while(i+1<s.length() && Character.isDigit(s.charAt(i+1))) {
                    cur = 10*cur + s.charAt(++i) - '0';
                }
                res += sign * cur;
            } else if(c=='-') {
                sign = -1;
            } else if(c=='+') {
                sign = 1;
            } else if( c=='(') {
                stack.push(res);
                res = 0;
                stack.push(sign);
                sign = 1;
            } else if(c==')') {
                res = stack.pop() * res + stack.pop();
                sign = 1;
            }
        }
        return res;
    }
}

只用了一个栈,网上也有别的方法用了数字栈和符号栈,还有其他的标识符,感觉很麻烦,就以大神的代码为例ba 

(1)res:最后计算器返回值是res,中间也复用了res作为括号内部的计算结果

(2)sign:标识符,+号表示为+1,-号表示为-1,很容易理解

(3)char c = s.charAt(i); charAt(i)取i位置的字符 

(4)Character.isDigit(c) 

http://www.51gjie.com/java/597.html

(5)int cur = c-'0';   将字符格式的数字转换为整型数字

(6)cur = 10*cur + s.charAt(++i) - '0';

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值