Problem:
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.
Solution:
字符串分成两种情况:数字num和运算符op,结果设为res,考虑到先乘除后加减的运算法则,设中间数mid优先计算乘除,再与res相加.
*> C++ version
1 class Solution { 2 public: 3 int calculate(string s) 4 { 5 int res=0, num=0, op=‘+‘, i=0, mid=0; 6 while(i<s.size()) 7 { 8 num = 0; ////每一轮要初始化num 9 //获取一整个数字存储在num中 10 if(isdigit(s[i])) 11 { 12 while(i<s.size()&&isdigit(s[i])) //连续数字字符作一个数 13 { 14 num = num*10+(s[i]-‘0‘); 15 i++; 16 } 17 18 //获取运算符存储在op中 19 if(op==‘+‘||op==‘-‘) 20 { 21 res = res+mid; 22 mid = num*(op==‘-‘?-1:1); 23 } 24 else if(op==‘/‘) 25 { 26 mid = mid/num; 27 } 28 else if(op==‘*‘) 29 { 30 mid = mid*num; 31 } 32 } 33 else if(s[i]==‘ ‘) //不要漏了开头空格这种情况= - =它喵被摆了一道 34 i++; 35 else 36 { 37 op=s[i]; 38 i++; 39 } 40 } 41 res = res+mid; 42 return res; 43 } 44 };
时间: 2024-10-07 04:12:38