Last active
July 6, 2020 16:27
-
-
Save Slakah/d407ff6b2896ff05f442c44a9a341f65 to your computer and use it in GitHub Desktop.
This file contains 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
/** | |
* Evaluate simple math expressions, supports add/times. | |
* Operator precedence is observed. | |
* e.g. in the expression 5+3*2, 3*2 would be evaluated first, leading to the final result of 11. | |
*/ | |
def eval(expr: String): Int = { | |
var i = 0 | |
var result = 0 | |
var num = 0 | |
while (i < expr.size) { | |
expr(i) match { | |
case '*' => | |
i = i + 1 | |
var num2 = 0 | |
while (i < expr.size && expr(i) != '+' && expr(i) != '*') { | |
num2 = (num2 * 10) + expr(i).asDigit | |
i = i + 1 | |
} | |
num = num * num2 | |
case '+' => | |
result = result + num | |
num = 0 | |
i = i + 1 | |
case c => | |
num = (num * 10) + c.asDigit | |
i = i + 1 | |
} | |
} | |
result + num | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment