假设我们有一个数字n。我们必须显示从1到n的所有数字的字符串表示形式,但是有一些限制。
如果该数字可被3整除,请写Fizz而不是数字
如果数字可以被5整除,请写Buzz代替数字
如果该数字可以同时被3和5整除,请写FizzBuzz而不是数字
为了解决这个问题,我们将遵循以下步骤-
对于从1到n的所有数字,
如果一个数字可以同时被3和5整除,则打印“ FizzBuzz”
否则,当数字可被3整除时,请打印“ Fizz”
否则,如果数字可以被5整除,则打印“ Buzz”
否则,将数字写为字符串
让我们看下面的实现以更好地理解-
class Solution(object): def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ result = [] for i in range(1,n+1): if i% 3== 0 and i%5==0: result.append("FizzBuzz") elif i %3==0: result.append("Fizz") elif i% 5 == 0: result.append("Buzz") else: result.append(str(i)) return result ob1 = Solution()print(ob1.fizzBuzz(30))
30
输出结果
["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz", "13","14","FizzBuzz","16","17","Fizz","19","Buzz","Fizz","22","23", "Fizz","Buzz","26","Fizz","28","29","FizzBuzz"]