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”.
题目大意: 输出一个从1到n的字符串数组
能被3整除的用“Fizz”代替数字,能被5整除的用“Buzz”代替数字,
能被3和5整除的用“FizzBuzz”代替数字,其余均用数字表示。
列表内容
Example: n = 15, Return: [ "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz" ]代码如下
C++
class Solution {
public:
vector<string> fizzBuzz(int n) {
vector<string> A;
for(int i=1;i<=n;i++)
{
if(i%15 == 0)
A.push_back("FizzBuzz");
else if(i%3 == 0)
A.push_back("Fizz");
else if(i%5 == 0)
A.push_back("Buzz");
else
A.push_back(to_string(i));
}
return A;
}
};
该题目读懂题意就能做。
本文介绍了一个经典的编程面试题——FizzBuzz问题。对于1到n的每个数字,如果数字能被3整除则输出“Fizz”,能被5整除则输出“Buzz”,同时被3和5整除则输出“FizzBuzz”,其他情况输出该数字本身。提供了C++实现代码。
682

被折叠的 条评论
为什么被折叠?



