Sunday, November 22, 2015

SimpleCalculator

Problem:

 TopCoder Problem Statement - SimpleCalculator Single Round Match 178 Round 1 - Division II, Level One

Overview:

Implement a simple calculator that can handle addition, subtraction, multiplications, and division.

Java Source:
1 public class SimpleCalculator {
2
3  public int calculate(String input) {
4
5   String[] ints = input.split("[+\\-\\*\\/]");
6
7   char op = input.charAt(ints.length());
8
9   int i1 = Integer.parseInt(ints);
10   int i2 = Integer.parseInt(ints);
11
12   if ('+' == op) return i1 + i2;
13   if ('-' == op) return i1 - i2;
14   if ('*' == op) return i1 * i2;
15   return i1 / i2;
16
17  }
18
19 }
Notes:

The only tricky part here is parsing the input to obtain the two integers and the operand. We can use the regular expression on line 5 for this. This will look for any of the characters (+, -, *, or /) and split the input into the integer that comes before and after the operator. When constructing the regular expression, you'll need to use \\ to escape some of the characters.

int will hold the first number. Thus, we can obtain the operator buy using the length of int. This is done on line 7. We can use Integer.parseInt() to get the integer values from the strings.

Then it's a simple matter of checking the value of the operator and performing the correct operation.