[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,返回1~n对应的字符串,其中3的整数倍用“Fizz”表示,5的倍数用“Buzz”表示,既是3的倍数又是5的倍数用“FizzBuzz”表示。定义一个string类型的vector,从1到n,依次判断是否是15、5、3的倍数相应赋值即可。

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

猜你喜欢

转载自blog.csdn.net/weixin_41814716/article/details/85679599