标签:
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.
/* 题目已知: 1.只包含非负整数,加减乘除,空格 2.假设输入一直合法 涉及的几个点: 1.数字分割 2.字符串转整数 3.运算符的优先级 可能隐藏的点: 大数 测试案例: "0" "1+0" "1+10" " 13 + 24 " " 23+ 34*3 /2 " " 12 - 7*3/2 + 35/7-3 " " 7*2/3 + 9" "12 - 7*3/2 + 35/7" */ class Solution { public: int calculate(string s) { int size = s.size(); long long int exp_res = 0,res=0; long int num =0; bool has_pre_op = false; char pre_op; for(int i=0;i<size;i++){ if(s[i]==‘ ‘) continue; if(isdigit(s[i])){ num = num*10+(s[i]-‘0‘); if(i+1 == size || !isdigit(s[i+1])){//如果下一个位置是最后一个位置,或者下一个位置不是数字了 if(has_pre_op){//当前运算数之前有操作符 if(pre_op==‘+‘){ exp_res = num; }else if(pre_op==‘-‘){ exp_res = -num; }else if(pre_op==‘*‘){ exp_res *= num; }else{ exp_res /= num; } }else{ exp_res = num; } } }else{ if(s[i]==‘+‘ || s[i]==‘-‘){ res += exp_res; } pre_op = s[i]; has_pre_op = true; num=0; } } return res+exp_res; } };
标签:
原文地址:http://www.cnblogs.com/zengzy/p/5037195.html