题目描述:
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”.
Example:
n = 15, Return: [ "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz" ]
解题思路:
直接代码。
代码:
1 class Solution { 2 public: 3 vector<string> fizzBuzz(int n) { 4 vector<string> ret; 5 for (int num = 1; num <= n; ++num) { 6 string tmp; 7 if (num % 3 == 0) 8 tmp += "Fizz"; 9 if (num % 5 == 0) 10 tmp += "Buzz"; 11 if (tmp.size() > 0) { 12 ret.push_back(tmp); 13 continue; 14 } 15 else 16 tmp += to_string(num); 17 ret.push_back(tmp); 18 } 19 return ret; 20 } 21 };