[LeetCode]412. Fizz Buzz

来源:互联网 发布:双代号网络时间参数 编辑:程序博客网 时间:2024/05/09 14:24

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

题目大意: 输出一个从1到n的字符串数组
能被3整除的用“Fizz”代替数字,能被5整除的用“Buzz”代替数字,
能被3和5整除的用“FizzBuzz”代替数字,其余均用数字表示。

  • 列表内容

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

    代码如下

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

该题目读懂题意就能做。

0 0
原创粉丝点击