Hard-题目35:224. Basic Calculator

转载 2016年05月31日 23:45:18

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;
}

相关文章推荐

第一周 leetcode 224. Basic Calculator(hard)

第一周 leetcode 224. Basic Calculator(hard)题目描述: Implement a basic calculator to evaluate a simple ex...
  • renzhff
  • renzhff
  • 2017年03月13日 20:25
  • 87

leetcode 224 Basic Calculator

1. 问题描述  计算字符串表达式的值,表达式中只含有(,),+,-,空格和非负整数。例如:   “1 + 1” = 2   ” 2-1 + 2 ” = 3   “(1+(4+5+2)-3)+(...

LeetCode-224.Basic Calculator

https://leetcode.com/problems/basic-calculator/ Implement a basic calculator to evaluate a simple ...

【leetcode】224. Basic Calculator

一、题目描述 Implement a basic calculator to evaluate a simple expression string. The expression s...

LeetCode 224. Basic Calculator

LeetCode 第224题 Basic Calculator JAVA语言实现

224-m-Basic Calculator

有括号的运算,只有加减运算。很明显本题只考察括号匹配没有再加入乘除,否则就真是半个计算器的工程了。由于我是先写了计算器二式,所以本题也想用一次扫描就出结果。但由于有括号要考虑出栈,要考虑单个括号括的数...

LeetCode No.224 Basic Calculator

LeetCode No.224 Basic Calculator

LeetCode(224) Basic Calculator

题目Implement a basic calculator to evaluate a simple expression string.The expression string may cont...
  • fly_yr
  • fly_yr
  • 2015年12月09日 14:00
  • 769

LeetCode-224. Basic Calculator (JAVA)实现计算器

224. Basic Calculator Implement a basic calculator to evaluate a simple expression string. The ...

[LeetCode]224. Basic Calculator

Implement a basic calculator to evaluate a simple expression string. The expression string may co...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Hard-题目35:224. Basic Calculator
举报原因:
原因补充:

(最多只允许输入30个字)