Evaluate mathematical expression
Description:
Instructions
Given a mathematical expression as a string you must return the result as a number.
Numbers
Number may be both whole numbers and/or decimal numbers. The same goes for the returned result.
Operators
You need to support the following mathematical operators:
- Multiplication
*
- Division
/
(as floating point division) - Addition
+
- Subtraction
-
Operators are always evaluated from left-to-right, and *
and /
must be evaluated before +
and -
.
Parentheses
You need to support multiple levels of nested parentheses, ex. (2 / (2 + 3.33) * 4) - -6
Whitespace
There may or may not be whitespace between numbers and operators.
An addition to this rule is that the minus sign (-
) used for negating numbers and parentheses will never be separated by whitespace. I.e all of the following are valid expressions.
1-1 // 0
1 -1 // 0
1- 1 // 0
1 - 1 // 0
1- -1 // 2
1 - -1 // 2
1--1 // 2
6 + -(4) // 2
6 + -( -4) // 10
And the following are invalid expressions
1 - - 1 // Invalid
1- - 1 // Invalid
6 + - (4) // Invalid
6 + -(- 4) // Invalid
Validation
You do not need to worry about validation - you will only receive valid mathematical expressions following the above rules.
Restricted APIs
NOTE: Both eval
and Function
are disabled.
Similar Kata:
Stats:
Created | Dec 10, 2013 |
Published | Dec 11, 2013 |
Warriors Trained | 41545 |
Total Skips | 4622 |
Total Code Submissions | 164668 |
Total Times Completed | 9870 |
JavaScript Completions | 3622 |
Java Completions | 1438 |
Ruby Completions | 443 |
PHP Completions | 259 |
TypeScript Completions | 310 |
Python Completions | 3196 |
C++ Completions | 540 |
Racket Completions | 16 |
Dart Completions | 39 |
Clojure Completions | 20 |
Haskell Completions | 123 |
C Completions | 148 |
Rust Completions | 217 |
COBOL Completions | 6 |
CoffeeScript Completions | 7 |
Total Stars | 2611 |
% of votes with a positive feedback rating | 94% of 1742 |
Total "Very Satisfied" Votes | 1560 |
Total "Somewhat Satisfied" Votes | 155 |
Total "Not Satisfied" Votes | 27 |
Total Rank Assessments | 9 |
Average Assessed Rank | 2 kyu |
Highest Assessed Rank | 2 kyu |
Lowest Assessed Rank | 4 kyu |