412. Fizz Buzz

【题目】

Write a program that outputs the string representation of numbers from 1 ton.

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

寫一個程序,輸出從1到n數字的字符串表示。

1.如果n是3的倍數,輸出“Fizz”;

2.如果n是5的倍數,輸出“Buzz”;

3.如果n同時是3和5的倍數,輸出“FizzBuzz”。

Example:

n = 15,

Return:
[
    "1",
    "2",
    "Fizz",
    "4",
    "Buzz",
    "Fizz",
    "7",
    "8",
    "Fizz",
    "Buzz",
    "11",
    "Fizz",
    "13",
    "14",
    "FizzBuzz"
]

【思路】

Easy Easy! Just do it!

【解法】

☆JAVA

class Solution {
    public List<String> fizzBuzz(int n) {
        List<String> resultList = new ArrayList<String>();
        if(n > 0){
            for(int i = 1 ; i <= n ; i++){
                if((i % 3 == 0)&&(i % 5 == 0)){resultList.add("FizzBuzz");continue;}
                if((i % 3 == 0)){resultList.add("Fizz");continue;}
                if((i % 5 == 0)){resultList.add("Buzz");continue;}
                resultList.add(i+"");
            }
        }
        return resultList;
    }
}

☆Python

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

results matching ""

    No results matching ""