LeetCode 412. Fizz Buzz

Problem:

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"
]

 

思路较为简单,首先考虑是否为15的倍数,然后考虑3,5的倍数,然后分情况处理即可。

runtime主要受int to string的影响。期初使用stringstream的方法,后换为C++ 11提供的to string。

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> re;
        for(int i = 1; i <= n; i++) {
            if (i % 15 == 0) 
                re.push_back("FizzBuzz");
            else if(i % 3 == 0) 
                re.push_back("Fizz");
            else if(i % 5 == 0) 
                re.push_back("Buzz");
            else
            {
                //stringstream ss;
                //ss << i;
                //re.push_back(ss.str());
                re.push_back(to_string(i));
            }
        }
        return re;
    }
};

 

posted @ 2016-10-28 12:02  yrwang  阅读(154)  评论(1编辑  收藏  举报