Problem Statement
When evaluating a mathematical expression, there is the possibility of ambiguity. If you wanted to know the result of "3 + 5 * 7", you might first evaluate the (3+5) and get 56, or first evaluate the (5*7) and get 38. This ambiguity can be resolved by using the order of operations: first do multiplication and division (from left to right), and then after all those are done, do addition and subtraction (again from left to right). Here, the correct result would be the 38.
While this is unambiguous, it certainly is somewhat annoying. You think it would be easier if people did all math from left to right, all the time, and want to make a simple expression evaluator to do so.
The expression will be given to you as a
Your method should return an int representing the value of the expression when evaluated from left to right.
Definition
- Class:
- NoOrderOfOperations
- Method:
- evaluate
- Parameters:
- String
- Returns:
- int
- Method signature:
- int evaluate(String expr)
- (be sure your method is public)
Constraints
- expr will be between 1 and 17 characters in length, inclusive.
- expr will contain an odd number of characters.
- expr will follow the format Digit Operator Digit Operator ... Digit, where each Digit is a single character from '0' to '9', and each Operator is either +, -, or *.
Examples
"3+5*7"
Returns: 56
First we add 3 + 5 to get 8. Then, we multiply 8 by 7 to get 56.
"4-8*9*1"
Returns: -36
Results can be negative.
"0"
Returns: 0
"1*2*3*4*5*6*7*8*9"
Returns: 362880
"5-7*9+2*0"
Returns: 0
"9*9*9*9*9*9*9*9*9"
Returns: 387420489
"9+8*3*2*3"
Returns: 306
"5+0+8+2+1"
Returns: 16
"1*9-3*3*7-9+5+1"
Returns: 123
"7*9*2*1"
Returns: 126
"7*9-2*0+2"
Returns: 2
"4*4+7"
Returns: 23
"8-5-4-7*2-9+6-2"
Returns: -21
"8*5-1+9-0+7*0-7"
Returns: -7
"6+2-3*3"
Returns: 15
"6-4+1*1+6+6"
Returns: 15
"3*0*5*8-2*9-1*3"
Returns: -57
"1-3*6-8+9+4-0-8"
Returns: -15
"1+5+5+3-9+9"
Returns: 14
"5*6*9+3-2+9"
Returns: 280
"3+4+1+8-7*4"
Returns: 36
"0+7-2*0"
Returns: 0
"6-7"
Returns: -1
"1+1*8+6*7-2-5+0"
Returns: 147
"6*5+0*1"
Returns: 30
"5-1*3"
Returns: 12
"6+4-7-9-4+3-5-0"
Returns: -12
"7+2+4+8*4+4-9"
Returns: 79
"2+6*3*9*5+5-7+6"
Returns: 1084
"3-3*4+5*1+9-3-5"
Returns: 6
"9+6*1"
Returns: 15
"5-1-0"
Returns: 4
"4+2*9"
Returns: 54
"7+3-2-1+6-8-5+8"
Returns: 8
"6-2+8-8*6"
Returns: 24
"8*2+7-2"
Returns: 21
"0*2-7-1+6*9-4"
Returns: -22
"8+0-2-8-0-1+3*9"
Returns: 0
"2*7*7-4+1*2+4*8+8"
Returns: 1560
"5-4*2*9+8"
Returns: 26
"2*6"
Returns: 12
"5*6+3"
Returns: 33
"4-8*9*1+5-2*3"
Returns: -99
"1*2*3*4*5*6*7*8*9"
Returns: 362880
"8"
Returns: 8
"5"
Returns: 5
"9*9*9*9*9*9*9*9"
Returns: 43046721
"5-7-4-6-7-8+2*4-3"
Returns: -103