-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleCalculator.php
More file actions
49 lines (40 loc) · 1.03 KB
/
SimpleCalculator.php
File metadata and controls
49 lines (40 loc) · 1.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<?php
/**
* This class encapsulates the logic to return the result of a calculation represented as a string
*
* It only supports addition and subtraction
* It does not support multiplication, division, brackets or indices
*
* Example input:
* "1 + 1 - 10 + 45"
*
* There will always be a space between operands and will always be a valid input
* No other text/characters are to be expected.
*
*/
class SimpleCalculator
{
/**
* Returns the result of a calculation represented as a string
*
* @param string $calculation
* @return int
* @throws Exception
*/
public static function calculate(string $calculation) : int
{
$chars = explode(' ',$calculation);
$total = (int)$chars[0];
for($i=3;$i<count($chars);$i+2):
switch ($chars[$i-1]):
case '+':
$total+=(int)$chars[$i];
break;
default:
$total-=(int)$chars[$i];
break;
endswitch;
endfor;
return $total;
}
}