Fizz Buzz Solutions in C++
Number 412
Difficulty Easy
Acceptance 62.3%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/fizz-buzz/// Author : Hao Chen// Date : 2016-11-13class Solution {public:vector<string> fizzBuzz_old_school_way(int n) {vector<string> result;for (int i=1; i<=n; i++) {if ( i%3 == 0 && i%5 ==0 ) {result.push_back("FizzBuzz");}else if (i%3 == 0) {result.push_back("Fizz");}else if (i%5 == 0) {result.push_back("Buzz");}else{result.push_back(std::to_string(i));}}return result;}class FizzBuzz {public:FizzBuzz() : x(0) {}string operator()() {x++;if ( x%3 == 0 && x%5 ==0 ) {return ("FizzBuzz");}else if (x%3 == 0) {return ("Fizz");}else if (x%5 == 0) {return("Buzz");}return std::to_string(x);}private:int x;};vector<string> fizzBuzz_cpp_way(int n) {vector<string> result(n);generate(result.begin(), result.end(), FizzBuzz());return result;}vector<string> fizzBuzz(int n) {//both method has same performanceif (rand() % 2 == 0) {return fizzBuzz_cpp_way(n);}return fizzBuzz_old_school_way(n);}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/fizz-buzz/description//// Author : liuyubobobo/// Time : 2018-09-23#include <iostream>#include <vector>using namespace std;/// Ad-Hoc/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:vector<string> fizzBuzz(int n) {vector<string> ret;for(int i = 1; i <= n; i ++)if(i % 15 == 0)ret.push_back("FizzBuzz");else if(i % 3 == 0)ret.push_back("Fizz");else if(i % 5 == 0)ret.push_back("Buzz");elseret.push_back(to_string(i));return ret;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/fizz-buzz/description//// Author : liuyubobobo/// Time : 2018-09-23#include <iostream>#include <vector>using namespace std;/// Using String Concatenation/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:vector<string> fizzBuzz(int n) {vector<string> ret;for(int i = 1; i <= n; i ++){string s = "";if(i % 3 == 0)s += "Fizz";if(i % 5 == 0)s += "Buzz";if(s == "")s = to_string(i);ret.push_back(s);}return ret;}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/fizz-buzz/description//// Author : liuyubobobo/// Time : 2018-09-23#include <iostream>#include <vector>#include <map>using namespace std;/// Using Map to make the logic more clear/// Time Complexity: O(n)/// Space Complexity: O(1)class Solution {public:vector<string> fizzBuzz(int n) {map<int, string> map = {{3, "Fizz"}, {5, "Buzz"}};vector<string> ret;for(int i = 1; i <= n; i ++){string s = "";for(const pair<int, string>& p: map)if(i % p.first == 0)s += p.second;if(s == "")s = to_string(i);ret.push_back(s);}return ret;}};int main() {return 0;}