227. Basic Calculator II
2015-12-21 21:37
246 查看
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:
Note: Do not use the
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
Note: Do not use the
evalbuilt-in library function.
class Solution { public: int calculate(string s) { stack<int> stack; int res = 0; int len = s.length(); for (int i = 0; i < len; i++) { char c = s[i]; if (isdigit(c)) { int cur = c - '0'; while (i + 1 < len && isdigit(s[i + 1])) { cur = cur * 10 + s[i + 1] - '0'; i++; } stack.push(cur); } else if (c == '+') { if (stack.size() == 1) stack.push(1); else { res = stack.top(); stack.pop(); res = res * stack.top(); stack.pop(); res = res + stack.top(); stack.pop(); stack.push(res); stack.push(1); } } else if (c == '-') { if (stack.size() == 1) stack.push(-1); else { res = stack.top(); stack.pop(); res = res * stack.top(); stack.pop(); res = res + stack.top(); stack.pop(); stack.push(res); stack.push(-1); } } else if (c == '*') { //avoid space while (i + 1 < len && !isdigit(s[i + 1])) { i++; } int cur = s[++i] - '0'; while (i + 1 < len && isdigit(s[i + 1])) { cur = cur * 10 + s[i + 1] - '0'; i++; } res = stack.top() * cur; stack.pop(); stack.push(res); } else if (c == '/') { while (i + 1 < len && s[i + 1] == ' ') { i++; } int cur = s[++i] - '0'; while (i + 1 < len && isdigit(s[i + 1])) { cur = cur * 10 + s[i + 1] - '0'; i++; } res = stack.top() / cur; stack.pop(); stack.push(res); } } if (stack.size() == 1) return stack.top(); else { res = stack.top(); stack.pop(); res = res * stack.top(); stack.pop(); res = res + stack.top(); return res; } } };
相关文章推荐
- 深入理解计算机系统 第二章 表示和操作信息
- CentOS 5/6.X 使用 EPEL YUM源
- 【codeforces 384E】Propagating tree 中文题意&题解&代码(c++)
- 项目的步骤,菜鸟的学习方法
- XMLHttpRequest 对象
- 数据库--iOS
- iOS开发拓展篇—CoreLocation定位服务
- 【菜鸟学Java】7:JSP的基本语法
- 设计模式-工厂模式(简单工厂,工厂方法,抽象工厂)
- 指针变量的作用
- Replication-Replication Distribution Subsystem: agent xxxxxx failed. Column names in each table must be unique
- cocos2dx怎样设置ios和Android横屏竖屏的几种方法
- $.extend,$.fn.extend,$.fn的区别
- Linux——Linux权限
- iOS屏幕尺寸和分辨率了解
- Linux经典面试题,看看你会几题?
- Android内存泄露
- Memcached十问十答
- SQL HAVING用法详解
- UIDynamic简单总结