FWNX-Evaluate Reverse Polish Notation -c++ VERSION-solution accepted
2013-12-28 04:32
302 查看
class Solution { public: int evalRPN(vector<string> &tokens) { int subresult = 0; stack<string> stack_op; for(int i = 0;i<tokens.size();++i) { if(tokens[i] != "+" && tokens[i] !="-" && tokens[i]!="*" && tokens[i]!="/") { stack_op.push(tokens[i]); } else { if(stack_op.size()==0) { cout << "stack is empty"<<endl; return -1;//-1 means wrong in the statement; } int right = atoi(stack_op.top().c_str()); stack_op.pop(); if(stack_op.size()==0) { cout << "stack is empty"<<endl; return -1;//-1 means wrong in the statement; } int left = atoi(stack_op.top().c_str()); stack_op.pop(); /* switch(tokens[i]) { case "+" : subresult = right+left;break; case "-" : subresult = left - right;break; case "*" : subresult = right*left;break; case "/" : subresult = left /right;break; default : { cout << "wrong oprend"<<endl; return -2; } }*/ if(tokens[i] == "+") { subresult = right+left; } else { if(tokens[i] == "-") { subresult = left - right; } else { if(tokens[i] == "*") { subresult = right*left; } else { if(tokens[i] == "/") { subresult = left /right; } else { cout << "wrong oprend"<<endl; return -2; } } } } char str[25] = {0}; sprintf(str,"%d",subresult); string sub_str_result(str); stack_op.push(sub_str_result); subresult = 0; } } int result = atoi(stack_op.top().c_str()); stack_op.pop(); return result; } };
http://oj.leetcode.com/problems/evaluate-reverse-polish-notation/
be care about the switch case
1 = it can only be used in the int in the switch area;
2 = it can use if else to change it; it can do everything;
3 = be careful about the stack empty qeustions
相关文章推荐
- 编译原理之学习 lua 3.1 (七) Closure 闭包支持
- 编译安装lua
- 以自定义方式加载 lua 模块
- lua面向对象编程之点号(.)与冒号(:)的差异详细比较
- 手游用lua实现逻辑的一些笔记
- lua mac环境搭建
- LUA 类型转换
- tolua++ api
- Lua的内存监测和回收
- 编译原理之学习 lua 3.0 (六) tag方法和可变数量参数
- Lua常用函数
- lua 标准库 基本函数
- protobuf-gen-lua 编译dll文件
- 编译原理之学习 lua 2.1 (五) 新增加的 fallback 和 oo 等支持
- Lua 语言 15 分钟快速入门
- Windows下使用第三方lua库
- Windows 下编译安装lua
- 转载和积累系列 - luci框架-LUA的一个web框架使用
- lua的栈
- 编译原理之学习 lua 1.1 笔记 (四) 多变量赋值和函数多返回值