LeetCode 224. 基本计算器

题目描述

🔥 224. 基本计算器

思路分析

思路描述

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
func calculate(s string) int {
	stack := make([]int, 0)
	num := 0
	sign := 1
	result := 0
	for i := 0; i < len(s); i++ {
		if isDigit(s[i]) {
			num = num*10 + int(s[i]-'0')
		} else if s[i] == '+' {
			result += sign * num
			num = 0
			sign = 1
		} else if s[i] == '-' {
			result += sign * num
			num = 0
			sign = -1
		} else if s[i] == '(' {
			stack = append(stack, result)
			stack = append(stack, sign)
			result = 0
			sign = 1
		} else if s[i] == ')' {
			result += sign * num
			num = 0
			result *= stack[len(stack)-1]
			result += stack[len(stack)-2]
			stack = stack[:len(stack)-2]
		}
	}
	return result + sign*num
}

func isDigit(ch byte) bool {
	return ch >= '0' && ch <= '9'
}

🍏 点击查看 Java 题解

1
write your code here

相似题目

题目 难度 题解
逆波兰表达式求值 Medium  
基本计算器 II Medium  
为运算表达式设计优先级 Medium  
给表达式添加运算符 Hard  
基本计算器 III Hard  
本文作者:
本文链接: https://hgnulb.github.io/blog/36902199
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!