龙熠的技术小站

Leetcode : 412 Fizz Buzz

Fizz Buzz 是一种训练小朋友学习除法的玩具,当一个数字可以整除3的时候,输出Fizz,当一个数字可以整除5的时候,输出Buzz,如果两者都满足,输出FizzBuzz


题目

1
2
3
4
5
描述
Write a program that outputs the string representation of numbers from 1 to n.
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”.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
例子:
n = 15,
Return:
[
"1",
"2",
"Fizz",
"4",
"Buzz",
"Fizz",
"7",
"8",
"Fizz",
"Buzz",
"11",
"Fizz",
"13",
"14",
"FizzBuzz"
]

解题思路

这个题比较简单,余3等于0,则显示Fizz,余5等于0,则显示Buzz,如果余3余5都等于0,则显示FizzBuzz

最后返回一个字符串数组

本题难度大的地方在于如何优化运行速度

解题

Language : swift

Runtime : 40ms

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
func fizzBuzz(_ n: Int) -> [String] {
var list : Array<String> = []
for a in 1...n {
var re : String = ""
if (a % 3 == 0) {
re = "Fizz"
}
if (a % 5 == 0) {
re += "Buzz"
}
if (re.lengthOfBytes(using: String.Encoding.utf8) == 0) {
re = String(a)
}
list.append(re)
}
return list
}
}
分享