leetcode 日经贴,Cpp code -Basic Calculator
2015-06-11 18:52
621 查看
Basic Calculator
class Solution { private: char token; int pos, num; stack<char> ops; stack<int> vals; int getpriority(char op) { int ret = 0; switch(op) { case '(': ret = 4; break; case '+': case '-': ret = 2; break; case ')': ret = 1; break; case 'd': ret = 0; break; default: ret = -1; break; } return ret; } void next_token(const string &s) { while (pos < s.length() && s[pos] == ' ') { ++pos; } if (pos >= s.length()) { token = '$'; } else if (s[pos] < '0' || s[pos] > '9') { token = s[pos]; ++pos; } else { token = 'd'; num = 0; while (pos < s.length() && s[pos] >= '0' && s[pos] <= '9') { num = num * 10 + int(s[pos++] - '0'); } } } public: int calculate(string s) { while (!ops.empty()) { ops.pop(); } while (!vals.empty()) { vals.pop(); } pos = 0; int ans; while (true) { next_token(s); if (token == 'd') { vals.push(num); } else if (token == '$') { if (!vals.empty()) { int a = vals.top(); vals.pop(); while (!ops.empty()) { int b = vals.top(); vals.pop(); char ch = ops.top(); ops.pop(); if (ch == '+') { a += b; } else { a = b - a; } } ans = a; } break; } else { while (!ops.empty() && getpriority(ops.top()) >= getpriority(token)) { char ch = ops.top(); if ((ch == '+' || ch == '-') && !vals.empty()) { int a = vals.top(); vals.pop(); if (vals.empty()) { vals.push(a); break; } int b = vals.top(); vals.pop(); ops.pop(); if (ch == '+') { vals.push(a + b); } else { vals.push(b - a); } } else { break; } } if (token == ')') { ops.pop(); } else { ops.push(token); } } } return ans; } };
相关文章推荐
- 简单栈的c语言实现
- 对VC++下Debug模式和Release模式的简要分析
- LeetCode 之 Pascal's Triangle — C++ 实现
- LeetCode 之 Merge Sorted Array — C++ 实现
- 行参和实参的区别 原文说的是c++的 借鉴一下吧
- 行参和实参的区别 原文说的是c++的 借鉴一下吧
- C++学习笔记(3) 数组
- 类型转换
- 提高C++程序运行效率的10个简单方法
- [转]C语言之单向链表的创建插入删除等功能
- Win7下vc++6.0打开项目Microsoft(R) Developer Studio以及Unable to register this add-in because its DLLRegist
- 浅谈C++中指针和引用的区别
- C++ 深入理解 字符串 和 数组
- 黑马程序员-C语言算法练习
- 指向指针的指针,彻底搞定C++指针
- C/C++中的预编译指令
- MFC完全自绘Tab控件,支持图片背景
- c++学习笔记(4.c++中新的关键字)
- C++中lower_bound函数和upper_bound函数
- C++ 10.4 关联容器-----set 类型