LoginSignup
0
0

概要

文系(体育科)卒業の僕が、人並みのアルゴリズムを身につけるためにLeetCodeを初めてみました。
日本だとAtCoderが一般的なようですが、海外エンジニアへの憧れを持つ僕はLeetCodeを選びました。

フロントの言語しかほぼ触ったことがないのでJavaScriptでやっていこうと思います。

問題

2665. Counter II

問題文

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.

初期コード

/**
 * @param {integer} init
 * @return { increment: Function, decrement: Function, reset: Function }
 */
var createCounter = function(init) {
    
};

問題を整理すると...

  • createCounter関数の作成
    • 3つ関数を持つObjectreturnする
      • increment()
        • current valueに対して1ずつ増える
      • decrement()
        • current valueに対して1ずつ減る
      • reset()
        • current valueを初期値に戻して、初期値をreturnする

CleanShot 2024-06-27 at 05.40.03@2x.jpg
とあるので、連続して関数を実行したときに前の値が引き継がれているらしい。
なので下記のように書いてみました。

var createCounter = function(init) {
   return {
       increment(){
            currentValue = init++
            return currentValue;
       },

       decrement(){
            currentValue = init--
            return currentValue;
       },

       reset(){
            currentValue = init;
            return currentValue;
       }
   } 
};

ダメみたいです。
CleanShot 2024-06-27 at 05.41.11@2x.jpg

そもそも+されていない。init++の書き方が良くないのかな?
ということでMDNを見てみます。

やっぱりここに原因がありそうです🤔

x++;
++x;

オペランドに後置で演算子を付けると (例えば、 x++) 、インクリメント演算子はインクリメントしますが、インクリメント前の値を返します。

オペランドに前置で演算子を付けると (例えば、 ++x) 、インクリメント演算子はインクリメントし、インクリメント後の値を返します。

「へぇ」

なので5がcurrentValueにセットされていたのか。
ということは前置で演算子をつければ良さそうですね。

var createCounter = function(init) {
   return {
       increment(){
            currentValue = ++init
            return currentValue;
       },

       decrement(){
            currentValue = --init
            return currentValue;
       },

       reset(){
            currentValue = init;
            return currentValue;
       }
   } 
};

ダメみたいです。
CleanShot 2024-06-27 at 05.47.29@2x.jpg

initをそのまま使っているのが良くないのかな?initが書き変わらないように下記のようにしてみます。

var createCounter = function(init) {
    let currentValue = init;

   return {
       increment(){
            currentValue += 1;
            return currentValue;
       },

       decrement(){
            currentValue -= 1;
            return currentValue;
       },

       reset(){
            currentValue = init;
            return currentValue;
       }
   } 
};

いけた🎉

今日も今日とて力尽きたのでコードの最適化など気にせず提出します。

CleanShot 2024-06-27 at 06.01.03@2x.jpg

(いいスコアで草)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0