- Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path0224-basic-calculator.rb
83 lines (73 loc) · 1.95 KB
/
0224-basic-calculator.rb
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# frozen_string_literal: true
# 224. Basic Calculator
# https://leetcode.com/problems/basic-calculator
# Hard
=begin
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
Example 1:
Input: s = "1 + 1"
Output: 2
Example 2:
Input: s = " 2-1 + 2 "
Output: 3
Example 3:
Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23
Constraints:
1 <= s.length <= 3 * 105
s consists of digits, '+', '-', '(', ')', and ' '.
s represents a valid expression.
'+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid).
'-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid).
There will be no two consecutive operators in the input.
Every number and running calculation will fit in a signed 32-bit integer.
=end
# @param {String} s
# @return {Integer}
defcalculate(s)
last=s.size - 1
total=0
sign=1
current=0
is_char=->index{s[index].ord.between?(?0.ord, ?9.ord)}
stack=[]
(0...s.size).eachdo |i|
char=s[i]
if ?+ == char
sign=1
elsif ?- == char
sign= -1
elsif" " == char
elsif ?( == char
stack.push([total,sign])
total=0
sign=1
current=0
elsif ?) == char
prev_total,prev_sign=stack.pop()
current=0
total=prev_total + prev_sign * total
sign=0
elsifis_char[i]
current=current * 10 + char.to_i
iflast == i || ! is_char[i + 1]
total += sign * current
current=0
sign=0
end
end
end
total
end
# **************** #
# TEST #
# **************** #
require"test/unit"
classTest_calculate < Test::Unit::TestCase
deftest_
assert_equal2,calculate("1 + 1")
assert_equal3,calculate(" 2-1 + 2 ")
assert_equal23,calculate("(1+(4+5+2)-3)+(6+8)")
end
end