3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Swift ならではのコードを紹介します。

Swiftのswitch文は、caseラベルにパターンを指定できます。

この問題の場合は、nを3で割った余りと、nを5で割った余りのタプルをswitch文に指定して、caseラベルに取り得る値のパターンを指定します。

パターンの0は、余り=0ですから、3もしくは5の倍数であることを表し、_は任意の値を表します。もちろん、_0も含みますから、caseラベルを書く順番が重要です(上から順に評価されます)。

let N = Int(readLine()!)!
for n in 1 ... N {
    switch (n % 3, n % 5) {
        case (0, 0): print("Fizz Buzz") //3の倍数かつ5の倍数
        case (0, _): print("Fizz")      //3の倍数
        case (_, 0): print("Buzz")      //5の倍数
        case (_, _): print(n)           //上記以外
    }    
}
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz Buzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
Fizz Buzz

Paizaで見る

3
2
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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?