412. Fizz Buzz

Link: https://leetcode.com/problems/fizz-buzz/

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

題目翻譯:

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

但是對於三的倍數,它應該輸出“Fizz”而不是數字和五個輸出“Buzz”的倍數。對於三個和五個輸出“FizzBu​​zz”的倍數的數字。

程式思路:

很 easy 的題目,但不知道為啥遞交率才 59%。

class Solution {
public:
    vector<string> fizzBuzz(int n)
    {
        vector<string> res;
        for(int i = 1;i <= n;i++)
        {
            string foo;
            if(i%3 == 0)
            {
                foo += "Fizz";
            }
            if(i%5 == 0)
            {
                foo += "Buzz";
            }
            if(foo.length()==0)
            {
                foo += std::to_string(i);
            }
            res.push_back(foo);
        }
        return res;
    }
};

  轉載請註明: YuYan's blog 412. Fizz Buzz

  目錄