Skip to content

Commit c2e50f7

Browse files
committed
227. Basic Calculator II
1 parent 45916f8 commit c2e50f7

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,6 +331,7 @@ I have solved quite a number of problems from several topics. See the below tabl
331331
|17| **[636. Exclusive Time of Functions](https://tinyurl.com/y7fkfomp)** | [Python](https://tinyurl.com/wu6rdaw/636_Exclusive_Time_of_Functions.py), [Swift](https://tinyurl.com/wuja3c4/636_Exclusive_Time_of_Functions.swift)| [Art 1](https://tinyurl.com/yd5rtdkl) | Medium | Must check |
332332
|18| **[921. Minimum Add to Make Parentheses Valid](https://tinyurl.com/wjv6txp)** | [Python](https://tinyurl.com/wu6rdaw/921_Minimum_Add_to_Make_Parentheses_Valid.py), [Swift](https://tinyurl.com/wuja3c4/921_Minimum_Add_to_Make_Parentheses_Valid.swift)| --- | Medium | --- |
333333
|19| **[1209. Remove All Adjacent Duplicates in String II](https://tinyurl.com/y3e4gsgv)** | [Python](https://tinyurl.com/wu6rdaw/1209_Remove_All_Adjacent_Duplicates_in_String_II.py), [Swift](https://tinyurl.com/wuja3c4/1209_Remove_All_Adjacent_Duplicates_in_String_II.swift)| --- | Medium | --- |
334+
|20| **[227. Basic Calculator II](https://tinyurl.com/y5g4u5by)** | [Python](https://tinyurl.com/wu6rdaw/227_Basic_Calculator_II.py), [Swift](https://tinyurl.com/wuja3c4/227_Basic_Calculator_II.swift)| [Art 1](https://tinyurl.com/y3dnn3zl) | Medium | --- |
334335

335336
</p>
336337
</details>
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import Foundation
2+
class Solution {
3+
func calculate(_ s: String) -> Int {
4+
var expression: [String] = Array(s).map { String($0) }.filter { $0 != " " }
5+
var (stack, currentSign, rightNum) = ([Int](), "+", 0)
6+
for (index, value) in expression.enumerated() {
7+
if let num = Int(value) {
8+
rightNum = rightNum * 10 + num
9+
}
10+
if (index == expression.count - 1) || ["+", "-", "*", "/"].contains(value) {
11+
if currentSign == "+" {
12+
stack.append(rightNum)
13+
} else if currentSign == "-" {
14+
stack.append(0 - rightNum)
15+
} else if currentSign == "*" {
16+
let leftNum = stack.popLast()!
17+
stack.append(leftNum * rightNum)
18+
} else {
19+
let leftNum = stack.popLast()!
20+
stack.append(leftNum / rightNum)
21+
}
22+
currentSign = value
23+
rightNum = 0
24+
}
25+
}
26+
return stack.reduce(0) { $0 + $1 }
27+
}
28+
}

0 commit comments

Comments
 (0)