当前位置:网站首页>LeetCode#412. Fizz Buzz

LeetCode#412. Fizz Buzz

2022-07-06 15:21:00 Rufeng ZHHH

subject ( Power button ):

Give you an integer n , Find out from 1 To n Of each integer Fizz Buzz Express , And use string array answer( Subscript from 1 Start ) Return results , among :

answer[i] == "FizzBuzz" If i At the same time 3 and 5 Multiple .
answer[i] == "Fizz" If i yes 3 Multiple .
answer[i] == "Buzz" If i yes 5 Multiple .
answer[i] == i ( In string form ) If none of the above conditions are met .
 

Example 1:

Input :n = 3
Output :["1","2","Fizz"]
Example 2:

Input :n = 5
Output :["1","2","Fizz","4","Buzz"]

This question is not difficult , It can be written in two ways .

Method 1 :

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        ls=[]
        for i in range(1,n+1):
            if i%3==0 and i%5==0:
                ls.append("FizzBuzz")
            elif i%3==0:
                ls.append("Fizz")
            elif i%5==0:
                ls.append("Buzz")
            else:
                ls.append(str(i))
        return ls

Method 2 :

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        answer=[0]*n
        for i in range(1,n+1):
            if i%3==0 and i%5==0:
                answer[i-1]="FizzBuzz"
            elif i%3==0:
                answer[i-1]="Fizz"
            elif i%5==0:
                answer[i-1]="Buzz"
            else:
                answer[i-1]=str(i)
        return answer

原网站

版权声明
本文为[Rufeng ZHHH]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202131319092658.html