topic:
Write a program that outputs a string representation of numbers from 1 to n. 1. If n is a multiple of 3, output "Fizz"; 2. If n is a multiple of 5, output "Buzz"; 3. If n is a multiple of both 3 and 5, output "FizzBuzz". Example: n = 15, return: [ "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz" ]
Problem solving ideas:
1. n is divisible by 3 and 5 at the same time to output "FizzBuzz";
2. n can only be divisible by 3 to output "Fizz";
3. n can only be divisible by 5 to output "Buzz";
4. Other output numbers;
Code:
class Solution { public: vector<string> fizzBuzz(int n) { vector<string> res; for(int i = 1;i <= n;++i){ if(i%3 == 0 && i%5 == 0){ res.push_back("FizzBuzz"); continue; }else if(i%3 == 0){ res.push_back("Fizz"); continue; }else if(i%5 == 0){ res.push_back("Buzz"); continue; }else{ res.push_back(to_string(i)); } } return res; } };