首页 > 代码库 > 227. Basic Calculator II
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.
解题思路:当前操作符如果是低优先级则可以计算之前的,否则更新当前的操作数
class Solution { public: int calculate(string s) { stringstream in(‘+‘+s+‘+‘); char op; long res=0,temp=0,n; while(in>>op){ if(op == ‘+‘ || op == ‘-‘){ res += temp; in>>temp; temp *= 44-op; } else { in>>n; if(op == ‘*‘) temp *= n; else temp /= n; } } return res; } };
227. Basic Calculator II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。