leetcode: Basic Calculator
2016-02-13 11:06
363 查看
Implement a basic calculator to evaluate a simple expression string.
The expression string may contain open
You may assume that the given expression is always valid.
Some examples:
Note: Do not use the
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
evalbuilt-in library function.
class Solution { public: int calculate(string s) { stack<int> signs; int lastSign = 1; int curNum = 0; int retSum = 0; for (auto c: s) { if (c == '(') { signs.push(lastSign);//进栈主要用在有括号的情况,如果没有括号,就不需要有栈 } else if (c == ')') { signs.pop(); } else if (c >= '0' && c <= '9') { curNum = curNum * 10 + (c-'0'); } else if (c == '+' || c == '-') { retSum = retSum + lastSign * curNum; lastSign = (c == '+'? 1:-1); if (signs.size() > 0) lastSign = lastSign * signs.top(); curNum = 0; } } return retSum + lastSign * curNum; } };
相关文章推荐
- 动态规划——小胖办证
- Android:获取版本号
- chmod 777修改文件系统权限
- leetcode:Implement Trie (Prefix Tree)
- linux下ping的C语言实现
- 动态规划——DNA
- 利用集合完成,对员工系统的操作
- uva10755 - Garbage Heap
- 在一个Servlet中处理多个请求方法
- 集合 ArrayList
- leetcode:Happy Number
- 53个要点提高PHP编程效率
- 【WCF 2】理解WCF框架的简单小实例
- 【WCF 2】理解WCF框架的简单小实例
- 超长字符串换行处理
- 母牛问题
- <climits>头文件
- 加油小白
- URL结构
- leetcode:Largest Number