题目描述
给定整数n,按照如下规则打印从1到n的每个数:
- 如果这个数被3整除,打印fizz
- 如果这个数被5整除,打印buzz
- 如果这个数能同时被3和5整除,打印fizz buzz
- 如果这个数既不能被3整除也不能被5整除,打印数字本身
思路
简单题,如题目描述,实现即可。
C++代码
class Solution {
public:
/**
* @param n: An integer
* @return: A list of strings.
*/
vector<string> fizzBuzz(int n) {
// write your code here
std::vector<std::string> result(n);
const std::string timesOf3 = "fizz";
const std::string timesOf5 = "buzz";
const std::string timesOf15 = "fizz buzz";
for (int i = 1; i <= n; ++i) {
if (i % 3 == 0) {
result[i-1] = i % 5 == 0 ? timesOf15 : timesOf3;
} else {
result[i-1] = i % 5 == 0 ? timesOf5 : std::to_string(i);
}
}
return result;
}
};