LintCode: Fizz Buzz

Given number n. Print number from 1 to n. But:

  • when number is divided by 3, print "fizz".
  • when number is divided by 5, print "buzz".
  • when number is divided by both 3 and 5, print "fizz buzz".

Those easy level questions, it is important to make code clean.

#include <string>
#include <vector>
#include <iostream>
using namespace std;

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("fizz buzz");
        } else if(i % 3 == 0) {
            res.push_back("fizz");
        } else if(i % 5 == 0) {
            res.push_back("buzz");
        } else {
            res.push_back(to_string(i));
        }
    }
    return res;
}

int main(void) {
    vector<string> res = fizzBuzz(15);
    for(int i = 0; i < res.size(); ++i) {
        cout << res[i] << endl;
    }
    cout << endl;
}


你可能感兴趣的:(LintCode: Fizz Buzz)