Skip to content

Commit 01e6230

Browse files
authoredSep 15, 2023
feat: add solutions to lcci problem: No.16.26 (#1629)
No.16.26.Calculator
1 parent 8b1e22b commit 01e6230

File tree

7 files changed

+479
-2
lines changed

7 files changed

+479
-2
lines changed
 

‎lcci/16.26.Calculator/README.md

+171-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
## 题目描述
66

77
<!-- 这里写题目描述 -->
8+
89
<p>给定一个包含正整数、加(+)、减(-)、乘(*)、除(/)的算数表达式(括号除外),计算其结果。</p>
910
<p>表达式仅包含非负整数,<code>+</code>, <code>-</code> ,<code>*</code>,<code>/</code> 四种运算符和空格&nbsp;<code>&nbsp;</code>。 整数除法仅保留整数部分。</p>
1011
<p><strong>示例&nbsp;1:</strong></p>
@@ -27,22 +28,191 @@
2728
## 解法
2829

2930
<!-- 这里可写通用的实现逻辑 -->
31+
32+
**方法一:栈**
33+
34+
我们可以用一个栈来保存数字,每次遇到运算符时,就将数字压入栈中。对于加减法,由于其优先级最低,我们可以直接将数字压入栈中;对于乘除法,由于其优先级较高,我们需要将栈顶元素取出,与当前数字进行乘除运算,再将结果压入栈中。
35+
36+
最后,将栈中所有元素求和即为答案。
37+
38+
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为字符串长度。
39+
3040
<!-- tabs:start -->
3141

3242
### **Python3**
3343

3444
<!-- 这里可写当前语言的特殊实现逻辑 -->
3545

3646
```python
37-
47+
class Solution:
48+
def calculate(self, s: str) -> int:
49+
n = len(s)
50+
x = 0
51+
sign = "+"
52+
stk = []
53+
for i, c in enumerate(s):
54+
if c.isdigit():
55+
x = x * 10 + ord(c) - ord("0")
56+
if i == n - 1 or c in "+-*/":
57+
match sign:
58+
case "+":
59+
stk.append(x)
60+
case "-":
61+
stk.append(-x)
62+
case "*":
63+
stk.append(stk.pop() * x)
64+
case "/":
65+
stk.append(int(stk.pop() / x))
66+
x = 0
67+
sign = c
68+
return sum(stk)
3869
```
3970

4071
### **Java**
4172

4273
<!-- 这里可写当前语言的特殊实现逻辑 -->
4374

4475
```java
76+
class Solution {
77+
public int calculate(String s) {
78+
int n = s.length();
79+
int x = 0;
80+
char sign = '+';
81+
Deque<Integer> stk = new ArrayDeque<>();
82+
for (int i = 0; i < n; ++i) {
83+
char c = s.charAt(i);
84+
if (Character.isDigit(c)) {
85+
x = x * 10 + (c - '0');
86+
}
87+
if (i == n - 1 || !Character.isDigit(c) && c != ' ') {
88+
switch (sign) {
89+
case '+' -> stk.push(x);
90+
case '-' -> stk.push(-x);
91+
case '*' -> stk.push(stk.pop() * x);
92+
case '/' -> stk.push(stk.pop() / x);
93+
}
94+
x = 0;
95+
sign = c;
96+
}
97+
}
98+
int ans = 0;
99+
while (!stk.isEmpty()) {
100+
ans += stk.pop();
101+
}
102+
return ans;
103+
}
104+
}
105+
```
106+
107+
### **C++**
108+
109+
```cpp
110+
class Solution {
111+
public:
112+
int calculate(string s) {
113+
int n = s.size();
114+
int x = 0;
115+
char sign = '+';
116+
stack<int> stk;
117+
for (int i = 0; i < n; ++i) {
118+
char c = s[i];
119+
if (isdigit(c)) {
120+
x = x * 10 + (c - '0');
121+
}
122+
if (i == n - 1 || !isdigit(c) && c != ' ') {
123+
if (sign == '+') {
124+
stk.push(x);
125+
} else if (sign == '-') {
126+
stk.push(-x);
127+
} else if (sign == '*') {
128+
int y = stk.top();
129+
stk.pop();
130+
stk.push(y * x);
131+
} else if (sign == '/') {
132+
int y = stk.top();
133+
stk.pop();
134+
stk.push(y / x);
135+
}
136+
x = 0;
137+
sign = c;
138+
}
139+
}
140+
int ans = 0;
141+
while (!stk.empty()) {
142+
ans += stk.top();
143+
stk.pop();
144+
}
145+
return ans;
146+
}
147+
};
148+
```
149+
150+
### **Go**
151+
152+
```go
153+
func calculate(s string) (ans int) {
154+
n := len(s)
155+
x := 0
156+
sign := '+'
157+
stk := []int{}
158+
for i := range s {
159+
if s[i] >= '0' && s[i] <= '9' {
160+
x = x*10 + int(s[i]-'0')
161+
}
162+
if i == n-1 || (s[i] != ' ' && (s[i] < '0' || s[i] > '9')) {
163+
switch sign {
164+
case '+':
165+
stk = append(stk, x)
166+
case '-':
167+
stk = append(stk, -x)
168+
case '*':
169+
stk[len(stk)-1] *= x
170+
case '/':
171+
stk[len(stk)-1] /= x
172+
}
173+
x = 0
174+
sign = rune(s[i])
175+
}
176+
}
177+
for _, x := range stk {
178+
ans += x
179+
}
180+
return
181+
}
182+
```
45183

184+
### **TypeScript**
185+
186+
```ts
187+
function calculate(s: string): number {
188+
const n = s.length;
189+
let x = 0;
190+
let sign = '+';
191+
const stk: number[] = [];
192+
for (let i = 0; i < n; ++i) {
193+
if (!isNaN(Number(s[i])) && s[i] !== ' ') {
194+
x = x * 10 + s[i].charCodeAt(0) - '0'.charCodeAt(0);
195+
}
196+
if (i === n - 1 || (isNaN(Number(s[i])) && s[i] !== ' ')) {
197+
switch (sign) {
198+
case '+':
199+
stk.push(x);
200+
break;
201+
case '-':
202+
stk.push(-x);
203+
break;
204+
case '*':
205+
stk.push(stk.pop()! * x);
206+
break;
207+
default:
208+
stk.push((stk.pop()! / x) | 0);
209+
}
210+
x = 0;
211+
sign = s[i];
212+
}
213+
}
214+
return stk.reduce((x, y) => x + y);
215+
}
46216
```
47217

48218
### **...**

‎lcci/16.26.Calculator/README_EN.md

+161-1
Original file line numberDiff line numberDiff line change
@@ -42,13 +42,173 @@
4242
### **Python3**
4343

4444
```python
45-
45+
class Solution:
46+
def calculate(self, s: str) -> int:
47+
n = len(s)
48+
x = 0
49+
sign = "+"
50+
stk = []
51+
for i, c in enumerate(s):
52+
if c.isdigit():
53+
x = x * 10 + ord(c) - ord("0")
54+
if i == n - 1 or c in "+-*/":
55+
match sign:
56+
case "+":
57+
stk.append(x)
58+
case "-":
59+
stk.append(-x)
60+
case "*":
61+
stk.append(stk.pop() * x)
62+
case "/":
63+
stk.append(int(stk.pop() / x))
64+
x = 0
65+
sign = c
66+
return sum(stk)
4667
```
4768

4869
### **Java**
4970

5071
```java
72+
class Solution {
73+
public int calculate(String s) {
74+
int n = s.length();
75+
int x = 0;
76+
char sign = '+';
77+
Deque<Integer> stk = new ArrayDeque<>();
78+
for (int i = 0; i < n; ++i) {
79+
char c = s.charAt(i);
80+
if (Character.isDigit(c)) {
81+
x = x * 10 + (c - '0');
82+
}
83+
if (i == n - 1 || !Character.isDigit(c) && c != ' ') {
84+
switch (sign) {
85+
case '+' -> stk.push(x);
86+
case '-' -> stk.push(-x);
87+
case '*' -> stk.push(stk.pop() * x);
88+
case '/' -> stk.push(stk.pop() / x);
89+
}
90+
x = 0;
91+
sign = c;
92+
}
93+
}
94+
int ans = 0;
95+
while (!stk.isEmpty()) {
96+
ans += stk.pop();
97+
}
98+
return ans;
99+
}
100+
}
101+
```
102+
103+
### **C++**
104+
105+
```cpp
106+
class Solution {
107+
public:
108+
int calculate(string s) {
109+
int n = s.size();
110+
int x = 0;
111+
char sign = '+';
112+
stack<int> stk;
113+
for (int i = 0; i < n; ++i) {
114+
char c = s[i];
115+
if (isdigit(c)) {
116+
x = x * 10 + (c - '0');
117+
}
118+
if (i == n - 1 || !isdigit(c) && c != ' ') {
119+
if (sign == '+') {
120+
stk.push(x);
121+
} else if (sign == '-') {
122+
stk.push(-x);
123+
} else if (sign == '*') {
124+
int y = stk.top();
125+
stk.pop();
126+
stk.push(y * x);
127+
} else if (sign == '/') {
128+
int y = stk.top();
129+
stk.pop();
130+
stk.push(y / x);
131+
}
132+
x = 0;
133+
sign = c;
134+
}
135+
}
136+
int ans = 0;
137+
while (!stk.empty()) {
138+
ans += stk.top();
139+
stk.pop();
140+
}
141+
return ans;
142+
}
143+
};
144+
```
145+
146+
### **Go**
147+
148+
```go
149+
func calculate(s string) (ans int) {
150+
n := len(s)
151+
x := 0
152+
sign := '+'
153+
stk := []int{}
154+
for i := range s {
155+
if s[i] >= '0' && s[i] <= '9' {
156+
x = x*10 + int(s[i]-'0')
157+
}
158+
if i == n-1 || (s[i] != ' ' && (s[i] < '0' || s[i] > '9')) {
159+
switch sign {
160+
case '+':
161+
stk = append(stk, x)
162+
case '-':
163+
stk = append(stk, -x)
164+
case '*':
165+
stk[len(stk)-1] *= x
166+
case '/':
167+
stk[len(stk)-1] /= x
168+
}
169+
x = 0
170+
sign = rune(s[i])
171+
}
172+
}
173+
for _, x := range stk {
174+
ans += x
175+
}
176+
return
177+
}
178+
```
51179

180+
### **TypeScript**
181+
182+
```ts
183+
function calculate(s: string): number {
184+
const n = s.length;
185+
let x = 0;
186+
let sign = '+';
187+
const stk: number[] = [];
188+
for (let i = 0; i < n; ++i) {
189+
if (!isNaN(Number(s[i])) && s[i] !== ' ') {
190+
x = x * 10 + s[i].charCodeAt(0) - '0'.charCodeAt(0);
191+
}
192+
if (i === n - 1 || (isNaN(Number(s[i])) && s[i] !== ' ')) {
193+
switch (sign) {
194+
case '+':
195+
stk.push(x);
196+
break;
197+
case '-':
198+
stk.push(-x);
199+
break;
200+
case '*':
201+
stk.push(stk.pop()! * x);
202+
break;
203+
default:
204+
stk.push((stk.pop()! / x) | 0);
205+
}
206+
x = 0;
207+
sign = s[i];
208+
}
209+
}
210+
return stk.reduce((x, y) => x + y);
211+
}
52212
```
53213

54214
### **...**

0 commit comments

Comments
 (0)
Please sign in to comment.