Wednesday, February 3, 2016

Simple Calculator

Simple Calculator

Given two integers a and b, an operator, choices:
+, -, *, /
Calculate a <operator> b.

Example
For a = 1, b = 2, operator = +, return 3.
For a = 10, b = 20, operator = *, return 200.
For a = 3, b = 2, operator = /, return 1. (not 1.5)
For a = 10, b = 11, operator = -, return -1.
Note
Use switch grammar to solve it




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public class Calculator {
    /**
      * @param a, b: Two integers.
      * @param operator: A character, +, -, *, /.
      */
    public int calculate(int a, char operator, int b) {
        /* your code */
        switch(operator) {
            case '+': 
                return a + b;
            case '-': 
                return a - b;
            case '*': 
                return a * b;
            case '/': 
                return a / b;
            default:
                return 0;
        }
    }
}