Hard-题目35:224. Basic Calculator

Hard-题目35:224. Basic Calculator
题目原文:
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
题目大意:
实现一个简易的计算器,对一个字符串求值。允许接受数字、+、-、括号。
题目分析:
用js中“危险的函数”eval水过去。
源码:略
Cmershen的碎碎念:
附一个很优美的java实现本题的代码:(来自discuss中的qiyidk大神)

public int calculate(String s) {
    if (s.length() == 0) return 0;
    s = "(" + s + ")";
    int[] p = {0};
    return eval(s, p);
}
// calculate value between parentheses
private int eval(String s, int[] p){
    int val = 0;
    int i = p[0]; 
    int oper = 1; //1:+ -1:-
    int num = 0;
    while(i < s.length()){
        char c = s.charAt(i);
        switch(c){
            case '+': val = val + oper * num; num = 0; oper = 1; i++; break;// end of number and set operator
            case '-': val = val + oper * num; num = 0; oper = -1; i++; break;// end of number and set operator
            case '(': p[0] = i + 1; val = val + oper * eval(s, p); i = p[0]; break; // start a new eval
            case ')': p[0] = i + 1; return val + oper * num; // end current eval and return. Note that we need to deal with the last num
            case ' ': i++; continue;
            default : num = num * 10 + c - '0'; i++;
        }
    }
    return val;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值