Calculator Class

Medium~20 min

Implement a Calculator class that performs basic arithmetic operations on a running result.

The Calculator class should support the following operations:

  • Calculator(initialValue) — Initialize the calculator with the given initialValue.
  • add(n) — Add n to the current result.
  • subtract(n) — Subtract n from the current result.
  • multiply(n) — Multiply the current result by n.
  • divide(n) — Divide the current result by n using integer division (truncate toward zero). If n is 0, do nothing.
  • getResult() — Return the current result.
  • reset() — Reset the result back to the initialValue.

Examples

Example 1
Input: ["Calculator","add","multiply","getResult","subtract","divide","getResult","reset","getResult"] [[10],[5],[2],[],[7],[3],[],[],[]]
Output: [null,null,null,30,null,null,7,null,10]
Explanation: Calculator calc = new Calculator(10); calc.add(5); // result = 10 + 5 = 15 calc.multiply(2); // result = 15 * 2 = 30 calc.getResult(); // return 30 calc.subtract(7); // result = 30 - 7 = 23 calc.divide(3); // result = 23 / 3 = 7 (integer division) calc.getResult(); // return 7 calc.reset(); // result = 10 (initial value) calc.getResult(); // return 10

Constraints

  • -10000 <= initialValue, n <= 10000
  • At most 1000 calls will be made to add, subtract, multiply, divide, getResult, and reset
  • Division by zero should be ignored (result unchanged)
  • Division truncates toward zero (e.g., 7/2=3, -7/2=-3)
Code
Ctrl+EnterRun|Ctrl+⇧+EnterSubmit
Output

Run your code to see results

Use Cmd+Enter to run