412. Fizz Buzz

来源:互联网 发布:上海银行淘宝金卡额度 编辑:程序博客网 时间:2024/05/16 11:36

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


原创粉丝点击