Writing a program, it outputs a number from 1 to n strings.
1. If n is a multiple of 3, the output "Fizz";
2. If n is a multiple of 5, the output "Buzz";
3. If n is a multiple of 3 and 5 at the same time, the output "FizzBuzz".
Example:
n = 15,
返回:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]
solution:
func fizzBuzz(_ n: Int) -> [String] {
guard n > 0 else {
return [""]
}
var array = [String]()
for item in 1...n {
if item % 3 == 0 && item % 5 == 0 {
array.append("FizzBuzz")
}else if item % 5 == 0{
array.append("Buzz")
}else if item % 3 == 0{
array.append("Fizz")
}else{
array.append(String(item))
}
}
return array
}