Leetcode 412.FizzBuzz

Title Description

Writing a program, it outputs a number from 1 to n strings.

1. 如果 n 是3的倍数,输出“Fizz”;

2. 如果 n 是5的倍数,输出“Buzz”;

3. 如果 n 同时是3和5的倍数,输出 “FizzBuzz”。

Example:

n = 15,

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

Topic analysis

Sieve element method similar thinking, all elements initialized to an empty string, then the elements of a multiple of 3 plus "Fizz", plus a multiple element 5 "Buzz", through the entire array and the array of hollow string assigned to the order.

Source

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
大专栏  Leetcode 412.FizzBuzz"line">class  {
public:
vector<string> fizzBuzz(int n) {
vector<string> res;
res.resize(n);
for(int i=1; i<=n/3; ++i) {
res[i*3-1] += "Fizz";
}
for(int i=1; i<=n/5; ++i) {
res[i*5-1] += "Buzz";
}
for(int i=0; i<n; ++i) {
if(res[i] == "") res[i]+=to_string(i+1);
}
return res;
}
};

Guess you like

Origin www.cnblogs.com/lijianming180/p/12041422.html