题目
写一个程序,输出从1到n数字的字符串表示。
- 如果n是3的倍数,输出”Fizz”;
- 如果n是5的倍数,输出”Buzz”;
- 如果n同时是3和5的倍数,输出”FizzBuzz”。

思路
一、暴力法
class Solution:def fizzBuzz(self, n: int) -> List[str]:ans = []for i in range(1, n+1):if i % 3 == 0:if i % 5 == 0:ans.append('FizzBuzz')else:ans.append('Fizz')elif i % 5 == 0:ans.append('Buzz')else:ans.append(str(i))return ans
填一下官方代码,写得确实优雅。
class Solution:def fizzBuzz(self, n):""":type n: int:rtype: List[str]"""# ans listans = []for num in range(1,n+1):divisible_by_3 = (num % 3 == 0)divisible_by_5 = (num % 5 == 0)if divisible_by_3 and divisible_by_5:# Divides by both 3 and 5, add FizzBuzzans.append("FizzBuzz")elif divisible_by_3:# Divides by 3, add Fizzans.append("Fizz")elif divisible_by_5:# Divides by 5, add Buzzans.append("Buzz")else:# Not divisible by 3 or 5, add the numberans.append(str(num))return ans
二、字符串连接

class Solution:def fizzBuzz(self, n):""":type n: int:rtype: List[str]"""# ans listans = []for num in range(1,n+1):divisible_by_3 = (num % 3 == 0)divisible_by_5 = (num % 5 == 0)num_ans_str = ""if divisible_by_3:# Divides by 3num_ans_str += "Fizz"if divisible_by_5:# Divides by 5num_ans_str += "Buzz"if not num_ans_str:# Not divisible by 3 or 5num_ans_str = str(num)# Append the current answer str to the ans listans.append(num_ans_str)return ans
三、更优雅且具有扩展性的实现:散列表
class Solution:def fizzBuzz(self, n):""":type n: int:rtype: List[str]"""# ans listans = []# Dictionary to store all fizzbuzz mappingsfizz_buzz_dict = {3 : "Fizz", 5 : "Buzz"}for num in range(1,n+1):num_ans_str = ""for key in fizz_buzz_dict.keys():# If the num is divisible by key,# then add the corresponding string mapping to current num_ans_strif num % key == 0:num_ans_str += fizz_buzz_dict[key]if not num_ans_str:num_ans_str = str(num)# Append the current answer str to the ans listans.append(num_ans_str)return ans
