LeetCode Fizz Buzz

LeetCode 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到n生成数字字符串,但是如果某个数能整除15,则生成FizzBuzz;能整除5,则生成Buzz;能整除3则生成Fizz。 发现<string>中的to_string()很好用:-) 完整代码如下: [cpp] class Solution { public: vector<string> fizzBuzz(int n) { vector<string> ans; for (int i = 1; i <= n; i++) { if (i % 15 == 0)ans.push_back("FizzBuzz"); else if (i % 5 == 0)ans.push_back("Buzz"); else if (i % 3 == 0)ans.push_back("Fizz"); else ans.push_back(to_string(i)); } return ans; } }; [/cpp] 本代码提交AC,用时3MS。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *