Created
November 20, 2025 21:20
-
-
Save skylar/06955e2ff855da3c65a7fe9c8e4be02c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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