Skip to content

Instantly share code, notes, and snippets.

@skylar
Created November 20, 2025 21:20
Show Gist options
  • Select an option

  • Save skylar/06955e2ff855da3c65a7fe9c8e4be02c to your computer and use it in GitHub Desktop.

Select an option

Save skylar/06955e2ff855da3c65a7fe9c8e4be02c to your computer and use it in GitHub Desktop.
def calculate(s)
stack = []
num = 0
op = '+'
s.each_char.with_index do |char, i|
if char.between?('0', '9')
num = num * 10 + char.to_i
end
if "+-*/".include?(char) || i == s.length - 1
case op
when '+'
stack.push(num)
when '-'
stack.push(-num)
when '*'
stack.push(stack.pop * num)
when '/'
last = stack.pop
last = last > 0 ? last / num : -(-last / num)
stack.push(last)
end
op = char
num = 0
end
end
stack.sum
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment