Total accepted:14291 Total submissions:64507 difficulty:medium
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.
Assume that the given expression was 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.
(M) Basic Calculator (H) Expression Add Operatorsthe expression is divided by +--with the expression part of multiplication as a whole, if the current operator is the +-sign, indicating that the result of the previous expression has been calculated, then the result of the previous expression is added to the output, if */indicates that the expression has not been completed.
/*title known: 1. Contains only nonnegative integers, subtraction, spaces 2. Assume that the input has been legally involved in several points: 1. Number Segmentation 2. String to Integer 3. The precedence of the operator may be hidden points: large number of test cases: "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"*/classSolution { Public: intCalculatestrings) {intSize =s.size (); Long Long intExp_res =0, res=0; Long intnum =0; BOOLHas_pre_op =false; CharPre_op; for(intI=0; i<size;i++){ if(s[i]==' ')Continue; if(IsDigit (S[i])) {num= num*Ten+ (s[i]-'0'); if(i+1= = Size | | !isdigit (s[i+1])){//if the next position is the last position, or the next position is not a number if(HAS_PRE_OP) {//There are operators before the current operand 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; } } returnres+Exp_res; }};
Next challenges: (M) Basic Calculator (H) Expression Add Operators
[String] Basic Calculator II