2665. Counter II
Description
Write a functionΒ createCounter. It should accept an initial integerΒ init. It should return an object with three functions.
The three functions are:
increment()Β increasesΒ the current value by 1 and then returns it.decrement()Β reduces the current value by 1 and then returns it.reset()Β sets the current value toΒinitΒ and then returns it.
Β
Example 1:
Input: init = 5, calls = ["increment","reset","decrement"] Output: [6,5,4] Explanation: const counter = createCounter(5); counter.increment(); // 6 counter.reset(); // 5 counter.decrement(); // 4
Example 2:
Input: init = 0, calls = ["increment","increment","decrement","reset","reset"] Output: [1,2,1,0,0] Explanation: const counter = createCounter(0); counter.increment(); // 1 counter.increment(); // 2 counter.decrement(); // 1 counter.reset(); // 0 counter.reset(); // 0
Β
Constraints:
-1000 <= init <= 10000 <= calls.length <= 1000calls[i]is one of "increment", "decrement" andΒ "reset"
Solutions
Solution 1
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 | |