[LeetCode] 412. Fizz Buzz

轉自LeetCode

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

<Solution>

It is a simple question. Use one for loop and output the corresponding string that follows the rules.

There is one tip to speed up. We can use constructor of vector to create enough spaces at the declaration because we know the final length from the input. Therefore, we can use index to access element rather than use push_back.

vector<string> res;        => need to use push_back()
vector<string> res(n, ""); => can use index to access
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.