题目描述

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

Example:

n = 15,

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

解法一

思路

这题就是寻找3和5的倍数,关键是匹配优先级的问题,可以照着以下流程来:

  1. 如果既是3的倍数,又是5的倍数,则输出"FizzBuzz"
  2. 如果是3的倍数,则输出"Fizz"
  3. 如果是5的倍数,则输出"Buzz"
  4. 否则输出数字的字符串表示。

python

class Solution(object):
    def fizzBuzz(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        result = []
        for item in range(1, n + 1):
            formatted = str(item)
            if item % 3 == 0 and item % 5 == 0:
                formatted = 'FizzBuzz'
            elif item % 3 == 0:
                formatted = 'Fizz'
            elif item % 5 == 0:
                formatted = 'Buzz'
            result.append(formatted)
        return result

Java

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

C++

class Solution {
public:
    vector <string> fizzBuzz(int n) {
        vector <string> result;
        for (int i = 1; i <= n; i++) {
            string formatted = to_string(i);
            if (i % 3 == 0 && i % 5 == 0) {
                formatted = "FizzBuzz";
            } else if (i % 3 == 0) {
                formatted = "Fizz";
            } else if (i % 5 == 0) {
                formatted = "Buzz";
            }
            result.push_back(formatted);
        }
        return result;
    }
};