Write a function or program than can do simple arithmetic (addition, subtraction, multiplication and division) in both base 10 and base 2.
The function will take a mathematical expression as input, and output the correct result in the correct base. The input will be n
numbers separated by one or several operators (+ - * /
).
If all input values contain only 0 and 1, all values are considered to be binary. If at least one digit is 2-9
, all values are considered to be base 10.
Rules:
- You can assume there will only be one operator between numbers (
10*-1
will not appear) - You can assume there will be no parentheses.
- Normal operator precedence (try the expression in the google calculator if you're in doubt).
- You can not assume there will only be integers
- There will be no leading zeros in input or output
- You can assume only valid input will be given
- You can assume all input values are positive (but the minus operator may make negative output possible,
1-2=-1
and10-100=-10
) - REPL is not accepted
- You may choose to take the input as separate arguments, or as a single argument, but the input has to be in the correct order.
- I.e. you may represent
1-2
with the input arguments1
,-
,2
, but not1
,2
,-
.
- I.e. you may represent
- You must accept the symbols
+ - * /
in the input, notplus
,minus
etc. - You must support floating point values (or up to the maximum limit of your language, however supporting only integers is not accepted).
eval
is accepted
Examples:
1+1
10
1010+10-1
1011
102+10-1
111
1+2+3
6
10*10*10
1000
11*11*11
11011
10*11*12+1
1321
10.1*10.1
110.01
20.2*20.2
408.04
10/5
2
110/10
11
Also accepted (optional line or comma-separated input):
10
+
10
-
1
11 <-- This is the output
This is code golf, so the shortest code in bytes will win.
110/10
, is11.0
acceptable? \$\endgroup\$