0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Leetcode easy: 412. Fizz Buzz(JavaScript)

Posted at

Leetcodeを始めたので記録しています。

やった問題

Given an integer n, return a string array answer (1-indexed) where:
answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
answer[i] == "Fizz" if i is divisible by 3.
answer[i] == "Buzz" if i is divisible by 5.
answer[i] == i (as a string) if none of the above conditions are true.

処理の流れをざっくり考える

  • 3で割り切れる
    • 5で割り切れる => "FizzBuzz"
    • 割り切れない => "Fizz"
  • 5で割り切れる => "Buzz"
  • 割り切れない => return n

最初に書いたコード

/**
 * @param {number} n
 * @return {string[]}
 */
var fizzBuzz = function(n) {
    const fizzbuzz_list = [];
    // in the range of n 
    for (let i = 1; i < n + 1; i++){
        // if n kan devided by 3
        if (i % 3 === 0){
            if (i % 5 === 0){
                element = 'FizzBuzz'
            } else {
                element = 'Fizz'
            }
        } else if (i % 5 === 0){
            element = 'Buzz'
        } else {
            element = String(i)
        }
        fizzbuzz_list.push(element);
    }
    
    return fizzbuzz_list
};

Runtime: 76 ms, faster than 86.26% of JavaScript online submissions for Fizz Buzz.
Memory Usage: 44.7 MB, less than 19.90% of JavaScript online submissions for Fizz Buzz.

調べたこと

概ね同じ内容である。
最短だとこんな解き方があるらしい。

  • for文の中で処理が一つの時は{ }を省略できる。
  • 論理演算子||は、xがtrueの場合は1つ目の値(演算子の左)、falseの場合は2つ目の値を返す(演算子の右)
  • for文の条件処理順。for文の条件の中でconsole.logの中で条件を書くとは思わなかった・・・

答えを見て改善したこと

特になし

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?