2665. Counter II | leetcode

阿榮-avatar-img
發佈於前端
更新於 發佈於 閱讀時間約 4 分鐘

2665. Counter II 題目

Write a function createCounter. It should accept an initial integer init. It should return an object with three functions.
編寫函式 createCounter。它應該接受初始整數 init。返回一個具有三個函式的物件。


The three functions are: 這三個函式分別為:

  • increment() increases the current value by 1 and then returns it.
    increment() 將當前值增加 1,然後返回它。
  • decrement() reduces the current value by 1 and then returns it.
    decrement()將當前值減小 1,然後返回它。
  • reset() sets the current value to init and then returns it.
    reset() 將當前值設置為 init,然後返回它。


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 <= 1000
  • 0 <= calls.length <= 1000
  • calls[i] is one of "increment", "decrement" and "reset"



解法參考

var createCounter = function(init) {
let currentValue = init;
return {
increment: () => currentValue+=1,
decrement: () => currentValue-=1,
reset: () => currentValue = init,
}
};
var createCounter = function(init) {
let currentValue = init;
return {
increment: () => ++currentValue,
decrement: () => --currentValue,
reset: () => currentValue = init,
}
};

不能寫 currentValue++ / currentValue--,因為會先回傳 currentValue,才進行 ++ / --。

或改寫成 進行 currentValue++ 後,再 return

var createCounter = function(init) {
let currentValue = init;
return {
increment: () => {
currentValue++
return currentValue;
},
decrement: () => {
currentValue--;
return currentValue;
},
reset: () => currentValue = init,
}
};
主要放程式學習筆記,分享 Creative Coding 相關內容、作品
留言
avatar-img
留言分享你的想法!

































































CSS 樣式採用規則:先看權重,再看誰後
* 避免命名衝突 * 避免非預期行為 * 避免非預期依賴
類別 (class) 是在 ES6 中引入,用來作為建立新物件的模板。它可以將程式碼封裝起來。
Express 是一個流行的 web 框架,使用 JavsScript 實現,執行在 node 環境上,主要用來寫後端應用。
npm(全名 Node Package Manager,node套件管理器)
CSS 樣式採用規則:先看權重,再看誰後
* 避免命名衝突 * 避免非預期行為 * 避免非預期依賴
類別 (class) 是在 ES6 中引入,用來作為建立新物件的模板。它可以將程式碼封裝起來。
Express 是一個流行的 web 框架,使用 JavsScript 實現,執行在 node 環境上,主要用來寫後端應用。
npm(全名 Node Package Manager,node套件管理器)
你可能也想看
Google News 追蹤
Thumbnail
題目敘述 題目會給我們一個定義好的類別和function介面,要求我們實作建構子和ping() function來滿足指定的需求。 RecentCounter類別的建構子 建構子應該初始化來電紀錄,內容為空(零筆資料) int ping(int t) t代表來電時刻,單位是毫秒m
Thumbnail
題目敘述 題目會給我們一個定義好的類別和function介面,要求我們實作建構子和ping() function來滿足指定的需求。 RecentCounter類別的建構子 建構子應該初始化來電紀錄,內容為空(零筆資料) int ping(int t) t代表來電時刻,單位是毫秒m