LeetCode412 Fizz Buzz

文章目录
  1. 1. 描述
  2. 2. 样例
  3. 3. 思路
  4. 4. 代码

描述

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
n = 15,

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

思路

找出 1 ~ n 中3的倍数、5的倍数以及15的倍数。对于3的倍数输出 “Fizz” ,5的倍数输出 “Buzz” ,15的倍数输出 “FizzBuzz” ,其余的输出对应的数字。

简单模拟,但是C++好像没有提供 int 转 string 的函数,还得自己动手写一个…

其实C++有提供int转string函数,叫to_string() ORZ…

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public:
string int2Str(int num) {
stringstream ss;
ss << num;
string str;
ss >> str;
return str;
}
vector<string> fizzBuzz(int n) {
vector<string> vec;
for (int i = 1; i <= n; ++i) {
if (i % 15 == 0) vec.push_back("FizzBuzz");
else if (i % 3 == 0) vec.push_back("Fizz");
else if (i % 5 == 0) vec.push_back("Buzz");
else vec.push_back(int2Str(i));
}
return vec;
}
};
分享到 评论