|
| 1 | +// LeetCode: https://leetcode.com/problems/basic-calculator/description/ |
| 2 | + |
| 3 | +import XCTest |
| 4 | + |
| 5 | +class Solution { |
| 6 | + func calculate(_ s: String) -> Int { |
| 7 | + var output: [Int] = [] |
| 8 | + let strArr = Array(s + "+") |
| 9 | + var open: [[Int]] = [] |
| 10 | + var num = 0 |
| 11 | + var sign: Character = "+" |
| 12 | + |
| 13 | + for ch in strArr { |
| 14 | + if ch >= "0" && ch <= "9" { |
| 15 | + num = num*10 + Int(String(ch))! |
| 16 | + } else if ch == "+" || ch == "-" { |
| 17 | + if open.count > 0 { |
| 18 | + open[0].append(sign == "+" ? num : -num) |
| 19 | + } else { |
| 20 | + output.append(sign == "+" ? num : -num) |
| 21 | + } |
| 22 | + num = 0 |
| 23 | + sign = ch |
| 24 | + } else if ch == "(" { |
| 25 | + var newSign = sign == "+" ? 1 : -1 |
| 26 | + if open.count > 0 { |
| 27 | + newSign *= open[0][0] |
| 28 | + } |
| 29 | + var arr: [Int] = [newSign] |
| 30 | + open.insert(arr, at: 0) |
| 31 | + sign = "+" |
| 32 | + } else if ch == ")" { |
| 33 | + if num != 0 { |
| 34 | + open[0].append(sign == "+" ? num : -num) |
| 35 | + num = 0 |
| 36 | + } |
| 37 | + let sign = open[0].removeFirst() |
| 38 | + output.append(sign * open[0].reduce(0, {x,y in |
| 39 | + x+y |
| 40 | + })) |
| 41 | + open.removeFirst() |
| 42 | + } |
| 43 | + } |
| 44 | + return output.reduce(0, {x,y in |
| 45 | + x+y |
| 46 | + }) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +class Tests: XCTestCase { |
| 51 | + let s = Solution() |
| 52 | + |
| 53 | + func testSample1() { |
| 54 | + let input = "1 + 1" |
| 55 | + let expected = 2 |
| 56 | + XCTAssertEqual(s.calculate(input), expected) |
| 57 | + } |
| 58 | + |
| 59 | + func testSample2() { |
| 60 | + let input = "(3-(2-(5-(9-(4)))))" |
| 61 | + let expected = 1 |
| 62 | + XCTAssertEqual(s.calculate(input), expected) |
| 63 | + } |
| 64 | + |
| 65 | + func testSample3() { |
| 66 | + let input = "(1+(4+5+2)-3)+(6+8)" |
| 67 | + let expected = 23 |
| 68 | + XCTAssertEqual(s.calculate(input), expected) |
| 69 | + } |
| 70 | + |
| 71 | + func testSample4() { |
| 72 | + let input = "1-(5)" |
| 73 | + let expected = -4 |
| 74 | + XCTAssertEqual(s.calculate(input), expected) |
| 75 | + } |
| 76 | + |
| 77 | + func testSample5() { |
| 78 | + let input = "(5-(1+(5)))" |
| 79 | + let expected = -1 |
| 80 | + XCTAssertEqual(s.calculate(input), expected) |
| 81 | + } |
| 82 | +} |
| 83 | + |
| 84 | +Tests.defaultTestSuite.run() |
0 commit comments