0%

[Leetcode]412. Fizz Buzz (C++)

题目描述

题目链接: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”.

例子

n = 15,

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

解题思路

Easy 的题目,没啥特别的做法,按顺序遍历一遍数字,每个数字判断是否能被 3 或 5 整除然后做相应调整即可,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <vector>
#include <string>

class Solution {
public:
std::vector<std::string> fizzBuzz(int n) {
std::vector<std::string> results;
for (int i = 1; i <= n; i++) {
std::string word;
if (i % 3 == 0) {
word += "Fizz";
}
if (i % 5 == 0) {
word += "Buzz";
}
if (word.length() == 0) {
word = std::to_string(i);
}
results.push_back(word);
}

return results;
}
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(n) <- 要求输出的空间