LeetCode-Basic Calculator II-解题报告
2015-06-28 21:29
417 查看
原题链接https://leetcode.com/problems/basic-calculator-ii/
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers,
You may assume that the given expression is always valid.
Some examples:
解题报告:
由于只有加减乘除,和空格符号没有括号之类的东西,所以可以使用栈数据结构,将数字和运算符压入栈中,当遇到的符号式乘号或者除号的时候
将栈顶弹出,并在读入一个操作数,将其运算后,在压入栈中。
最后栈中剩下的只是一些加减法。可以将其全部转换成加法的情况,例如1-2可以表示成1+(-2),方便code
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only non-negative integers,
+,
-,
*,
/operators and empty spaces. The integer division should truncate toward zero.
You may assume that the given expression is always valid.
Some examples:
"3+2*2" = 7 |
" 3/2 " = 1 |
" 3+5 / 2 " = 5 |
解题报告:
由于只有加减乘除,和空格符号没有括号之类的东西,所以可以使用栈数据结构,将数字和运算符压入栈中,当遇到的符号式乘号或者除号的时候
将栈顶弹出,并在读入一个操作数,将其运算后,在压入栈中。
最后栈中剩下的只是一些加减法。可以将其全部转换成加法的情况,例如1-2可以表示成1+(-2),方便code
class Solution { public: int calculate(string s) { if (s.length() == 0)return 0; stack<int>Stack; int op1, op2, i = 0, ans = 0; string str = ""; for (i = 0; i < s.length(); ++i)if (s[i] != ' ')str += s[i]; s = str; i = 0; op1 = stoi(s, i); Stack.push(op1); for (; i < s.length();) { char type = s[i]; i++; int op2 = stoi(s, i); if (type == '*') { op1 = Stack.top(); Stack.pop(); Stack.push(op1 * op2); } if (type == '/') { op1 = Stack.top(); Stack.pop(); Stack.push(op1 / op2); } if (type == '+') { Stack.push(-1); Stack.push(op2); } if (type == '-') { Stack.push(-2); Stack.push(op2); } } while (!Stack.empty()) { op2 = -1; op1 = Stack.top(); Stack.pop(); if (!Stack.empty()) { op2 = Stack.top(); Stack.pop(); } if (op2 == -1)ans += op1; if (op2 == -2)ans += (-op1); } return ans; } int stoi(string& s, int& pos) { int tmp = 0; while (s[pos] >= '0' && s[pos] <= '9' && pos < s.length()) { tmp = tmp * 10 + (s[pos] - '0'); pos++; } return tmp; } };
相关文章推荐
- opencv 数字图像处理-图像错切
- Linux 手动编译PHP 5.6
- 向集合中存储自定义对象是,自定义对象的设计
- 访问Index function 两次
- cJSON(Linux C)
- 面试jsp题动态包含和静态包含
- Material Design控件使用(三)
- linux文件空洞
- Objective-C 快速入门--基础(三)
- springmvc sitemesh json问题
- 记录是最好的开始
- 进程与线程
- 基于OpenCV的摄像机标定-翻译
- WPF——传实体类
- 机房重构的总结 (一)
- android程序入门
- 机器视觉光源学习总结——开孔背光源
- javascript延长作用域链
- nyoj 282 You are my brother
- 设计模式 随笔(二)