leetcode: Basic Calculator
来源:互联网 发布:java发音 编辑:程序博客网 时间:2024/06/15 03:44
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
/*Example: 7 - (6 - 5 - (4 - 3) - 2) - (1)Result : +7 - 6 + 5 + 4 - 3 + 2 - 1 The + -are signs just before '('.They are dealt with previous stack sign. Then they are saved in the stack to help decide the signs in the following "(..)" .*/class Solution {public: int calculate(string s) { stack<int> t; //previous sign just before the '(' t.push(1); //for all the signs those are not in the parentheses int sum = 0, temp = 0, lastSign = 1; for (auto c : s) { if (c == '(') t.push(lastSign); //save the sign just before the '(' else if (c == ')') t.pop(); if (c >= '0' && c <= '9'){ temp = temp * 10 + c - '0'; } if (c == '-' || c == '+'){ sum += lastSign*temp; //calculate the number before current sign temp = 0; lastSign = (c == '-' ? -1 : 1)*t.top(); //deal with the stack influencing sign } } sum += lastSign*temp; //calculate the last number return sum; }};
0 0
- 【LeetCode】Basic Calculator && Basic Calculator II
- LeetCode - Basic Calculator & Basic Calculator II
- Leetcode之Basic Calculator & Basic Calculator II
- [leetcode] Basic Calculator
- Basic Calculator - LeetCode 224
- LeetCode Basic Calculator
- leetcode:Basic Calculator
- [leetcode][math] Basic Calculator
- [LeetCode] Basic Calculator
- Leetcode 224: Basic Calculator
- leetcode 224 Basic Calculator
- [LeetCode] Basic Calculator II
- [leetcode] Basic Calculator II
- [Leetcode] Basic Calculator
- leetcode Basic Calculator
- leetcode Basic Calculator II
- LeetCode-Basic Calculator
- leetcode Basic Calculator 栈
- quartz源码分析(四)
- JAVA的反射机制
- 正确释放Vector的内存
- Triangle LOVE
- c++运算符重载总结
- leetcode: Basic Calculator
- 线段树
- hold 命令
- LeeetCode #84 Largest Rectangle in Histogram
- DQL、DML、DDL、DCL的概念与区别
- 禅与软件测试--创造性思维
- OC - NSStringAndNSMutableString
- dailyAdvice服务器与客户端
- 设计模式之代理模式