227. Basic Calculator II
Posted 积少成多
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了227. Basic Calculator II相关的知识,希望对你有一定的参考价值。
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
Note: Do not use the eval
built-in library function.
==================
基本的+,-,*,/计算,利用栈
====
思路:
申请两个栈,一个符号栈op,一个数字栈num,
代码:
class Solution { public: int calculate(string s) { stack<char> op; stack<int> num; const int n = s.size(); char ch; int tmp = 0; int a = 0; for(int i = 0;i<n;i++){ ch = s[i]; if(ch==‘ ‘) continue; else if(ch==‘*‘ || ch==‘/‘ || ch==‘+‘ || ch==‘-‘){ op.push(ch); }else if(isdigit(ch)){ tmp = tmp*10+ch-‘0‘; while(i<n && isdigit(ch=s[++i])){ tmp = tmp*10+ch-‘0‘; } if(!op.empty()){ char curr_op = op.top(); if(curr_op == ‘*‘){ int a = num.top();num.pop();op.pop(); num.push(a*tmp); }else if(curr_op == ‘/‘){ a = num.top();num.pop();op.pop(); num.push(a/tmp); }else{ if(curr_op == ‘-‘) tmp *=-1; num.push(tmp); } }else{ num.push(tmp); } tmp = 0; if(i==n) break; i--; } } while(!op.empty()){ int a = num.top();num.pop(); int b = num.top();num.pop(); //char ch = op.top(); op.pop(); num.push(a+b); }///while int re = num.top();num.pop(); return re; } };
以上是关于227. Basic Calculator II的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 227. 基本计算器 II(Basic Calculator II)