412. Fizz Buzz

云计算 waitig 540℃ 百度已收录 0评论

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”.

java

public class Solution {
    /*
     * @param n: An integer
     * @return: A list of strings.
     */
    public List<String> fizzBuzz(int n) {
        // write your code here
        ArrayList<String> results = new ArrayList<String>();
        for (int i = 1; i <= n; i++) {
            if (i % 15 == 0) {
                results.add("fizz buzz");
            } else if (i % 5 == 0) {
                results.add("buzz");
            } else if (i % 3 == 0) {
                results.add("fizz");
            } else {
                results.add(String.valueOf(i));
            }
        }
        return results;
    }
}

python

class Solution:
    """
    @param: n: An integer
    @return: A list of strings.
    """
    def fizzBuzz(self, n):
        # write your code here
        list = []
        for i in range(1, n + 1):
            if i % 3 == 0 and i % 5 != 0:
                list.append("fizz")
            elif i % 3 != 0 and i % 5 == 0:
                list.append("buzz")
            elif i % 3 == 0 and i % 5 == 0:
                list.append("fizz buzz")
            else:
                list.append(str(i))
        return list


本文由【waitig】发表在等英博客
本文固定链接:412. Fizz Buzz
欢迎关注本站官方公众号,每日都有干货分享!
等英博客官方公众号
点赞 (0)分享 (0)