Skip to content

Commit bcaf683

Browse files
committed
feat: Solution for Problem #412 - Fizz Buzz
1 parent 3fbea41 commit bcaf683

File tree

2 files changed

+85
-0
lines changed

2 files changed

+85
-0
lines changed
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/*:
2+
# 412. Fizz Buzz [Easy]
3+
https://leetcode.com/problems/fizz-buzz/
4+
5+
---
6+
7+
### Problem Statement:
8+
9+
Write a program that outputs the string representation of numbers from 1 to n.
10+
11+
But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.
12+
13+
14+
### Example:
15+
16+
```
17+
n = 15,
18+
19+
Return:
20+
[
21+
"1",
22+
"2",
23+
"Fizz",
24+
"4",
25+
"Buzz",
26+
"Fizz",
27+
"7",
28+
"8",
29+
"Fizz",
30+
"Buzz",
31+
"11",
32+
"Fizz",
33+
"13",
34+
"14",
35+
"FizzBuzz"
36+
]
37+
```
38+
39+
*/
40+
41+
42+
import UIKit
43+
44+
class Solution {
45+
func fizzBuzz(_ n: Int) -> [String] {
46+
guard n > 0 else { return [] }
47+
48+
var result = [String]()
49+
for i in 1...n {
50+
if i%15 == 0 {
51+
result.append("FizzBuzz")
52+
} else if i%3 == 0 {
53+
result.append("Fizz")
54+
} else if i%5 == 0 {
55+
result.append("Buzz")
56+
} else {
57+
result.append(String(i))
58+
}
59+
}
60+
return result
61+
}
62+
63+
func fizzBuzz1(_ n: Int) -> [String] {
64+
guard n > 0 else { return [] }
65+
66+
var result = [String]()
67+
for num in 1...n {
68+
if num % 3 == 0 {
69+
result.append(num % 5 == 0 ? "FizzBuzz" : "Fizz")
70+
} else {
71+
result.append(num % 5 == 0 ? "Buzz" : "\(num)")
72+
}
73+
74+
}
75+
return result
76+
}
77+
}
78+
79+
80+
let sol = Solution()
81+
sol.fizzBuzz(15)
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>

0 commit comments

Comments
 (0)