当前位置:网站首页>Force buckle 4_ 412. Fizz Buzz

Force buckle 4_ 412. Fizz Buzz

2022-07-08 02:15:00 Don't sleep in class

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"]

Example 3:

 Input :n = 15
 Output :["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]

source : Power button (LeetCode)

Java solution

class Solution {
    
    public List<String> fizzBuzz(int n) {
    
        List<String> lst = new ArrayList<String>();
        for (int i = 0; i < n; i++) {
    
            int num = i + 1;
            if (num % 3 == 0 && num % 5 == 0) lst.add("FizzBuzz");
            else if (num % 3 == 0) lst.add("Fizz");
            else if (num % 5 == 0) lst.add("Buzz");
            else lst.add(String.valueOf(num));
            //String.valueOf(num) take num Convert to string 
        }
        return lst;
    }
}

Python solution

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        ans = []
        for i in range(1, n + 1):
            s = ""
            if i % 3 == 0:
                s += "Fizz"
            if i % 5 == 0:
                s += "Buzz"
            if s == "":
                s = str(i)
            ans.append(s)
        return ans
原网站

版权声明
本文为[Don't sleep in class]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/189/202207080039142891.html