计算器一:

  • s 由整数和算符 (‘+’, ‘-‘, ‘*’, ‘/‘) 组成,中间由一些空格隔开
  • 如: “ 3+5 / 2 “
    1. func calculate(s string) (ans int) {
    2. // 前置计算符 + 栈实现
    3. stack := []int{}
    4. num, preSign := 0, '+'
    5. for i, ch := range s {
    6. isDigit := ch >= '0' && ch <= '9'
    7. if isDigit {
    8. num = num*10 + int(ch-'0')
    9. }
    10. if !isDigit && ch != ' ' || i == len(s)-1 {
    11. switch preSign {
    12. case '+':
    13. stack = append(stack, num)
    14. case '-':
    15. stack = append(stack, -num)
    16. case '*':
    17. stack[len(stack)-1] *= num
    18. case '/':
    19. stack[len(stack)-1] /= num
    20. }
    21. preSign = ch
    22. num = 0
    23. }
    24. }
    25. for _, v := range stack {
    26. ans += v
    27. }
    28. return
    29. }

计算器二:

  • s 由数字、’+’、’-‘、’(‘、’)’、和 ‘ ‘ 组成
  • 如:”(1+(4+5+2)-3)+(6+8)”

    1. func calculate(s string) int {
    2. nums, signs := []int{}, []int{}
    3. ans, sign := 0, 1
    4. for i := 0; i < len(s); i++ {
    5. if s[i] == ' ' {
    6. continue
    7. } else if s[i] == '+' || s[i] == '-' {
    8. sign = 1
    9. if s[i] == '-' {
    10. sign = -1
    11. }
    12. } else if s[i] >= '0' && s[i] <= '9' {
    13. num := 0
    14. for ; i < len(s) && s[i] >= '0' && s[i] <= '9'; i++ {
    15. num = num*10 + int(s[i] - '0')
    16. }
    17. i--
    18. ans = ans + sign*num
    19. } else if s[i] == '(' {
    20. nums = append(nums, ans)
    21. signs = append(signs, sign)
    22. ans, sign = 0, 1
    23. } else if s[i] == ')' {
    24. top := nums[len(nums)-1]
    25. nums = nums[:len(nums)-1]
    26. sign = signs[len(signs)-1]
    27. signs = signs[:len(signs)-1]
    28. ans = top + sign*ans
    29. }
    30. }
    31. return ans
    32. }

    计算器三:

  • 支持 + - * / ( )

  • “(2+6 3+5- (314/7+2)*5)+3”=-12
    1. class Solution {
    2. public:
    3. int calculate(string s) {
    4. int n = s.size(), num = 0, curRes = 0, res = 0;
    5. char op = '+';
    6. for (int i = 0; i < n; ++i) {
    7. char c = s[i];
    8. if (c >= '0' && c <= '9') {
    9. num = num * 10 + c - '0';
    10. } else if (c == '(') {
    11. int j = i, cnt = 0;
    12. for (; i < n; ++i) {
    13. if (s[i] == '(') ++cnt;
    14. if (s[i] == ')') --cnt;
    15. if (cnt == 0) break;
    16. }
    17. num = calculate(s.substr(j + 1, i - j - 1));
    18. }
    19. if (c == '+' || c == '-' || c == '*' || c == '/' || i == n - 1) {
    20. switch (op) {
    21. case '+': curRes += num; break;
    22. case '-': curRes -= num; break;
    23. case '*': curRes *= num; break;
    24. case '/': curRes /= num; break;
    25. }
    26. if (c == '+' || c == '-' || i == n - 1) {
    27. res += curRes;
    28. curRes = 0;
    29. }
    30. op = c;
    31. num = 0;
    32. }
    33. }
    34. return res;
    35. }
    36. };