412.Fizz Buzz
Write a program that outputs the string representation of numbers from 1 ton.
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”.
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格式。
My C++ code:
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> res(n) ;
for (int i = 1 ; i <= n ; ++ i)
{
if (i % 3 == 0 )
res[i - 1] += string("Fizz") ;
if (i % 5 == 0 )
res[i - 1] += string("Buzz") ;
if (res[i - 1] == "")
res[i - 1] += to_string(i) ;
}
return res ;
};