412. Fizz Buzz
Posted gsz-
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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”.
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 };
以上是关于412. Fizz Buzz的主要内容,如果未能解决你的问题,请参考以下文章