LeetCode 412. 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"
]

解析:

指定数值n,输出字符表示的每个数字,如果是3的倍数,则用Fizz代替;如果是5的倍数,则用Buzz代替;如果同时是3和5的倍数,则用FizzBuzz代替。

代码如下:

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

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据