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:

  1. "3+2*2" = 7
  2. " 3/2 " = 1
  3. " 3+5 / 2 " = 5

Note: Do not use the eval built-in library function.

题目翻译:
实现一个简易的计算器来对简单的字符串表达式求值。
字符串表达式只包含非负整数,+,-,*,/四种运算符,以及空格。整数除法向零取整。
给出的表达式都是有效的。
不要使用内置的eval函数。

题目分析:
通常对算术表达式求值都是用栈来实现的,但是鉴于本题的情形比较简单,所以可以不用栈来实现。
总体思路是,依次读入字符串里的字符,遇到符号的时候就进行运算。如果是乘除法,就把结果存入中间变量,如果是加减法就把结果存入最终结果。

用C++实现的时候,可以在循环中使用string类的find_first_not_of方法来跳过空格。
读到数字时,继续向后读,直到不是数字的字符,或者超出字符串长度为止。

代码如下:

  1. class Solution {
  2. public:
  3. int calculate(string s) {
  4. int result = 0, inter_res = 0, num = 0;
  5. char op = '+';
  6. char ch;
  7. for (int pos = s.find_first_not_of(' '); pos < s.size(); pos = s.find_first_not_of(' ', pos)) {
  8. ch = s[pos];
  9. if (ch >= '0' && ch <= '9') {
  10. int num = ch - '0';
  11. while (++pos < s.size() && s[pos] >= '0' && s[pos] <= '9')
  12. num = num * 10 + s[pos] - '0';
  13. switch (op) {
  14. case '+':
  15. inter_res += num;
  16. break;
  17. case '-':
  18. inter_res -= num;
  19. break;
  20. case '*':
  21. inter_res *= num;
  22. break;
  23. case '/':
  24. inter_res /= num;
  25. break;
  26. }
  27. }
  28. else {
  29. if (ch == '+' || ch == '-') {
  30. result += inter_res;
  31. inter_res = 0;
  32. }
  33. op = s[pos++];
  34. }
  35. }
  36. return result + inter_res;
  37. }
  38. };