LeetCode 412. Fizz Buzz

Posted zsy-blog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 412. Fizz Buzz相关的知识,希望对你有一定的参考价值。

技术图片

 

 使用散链表的字符串连接法。

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> ans;

        //Hash map to store all fizzbuzz mappings.
        map<int, string> fizzBuzzDict = {
            {3, "Fizz"},
            {5, "Buzz"} 
        };
    
        for (int num = 1; num <= n; ++num)
        {
            string numAnsStr = "";

            for (auto key : fizzBuzzDict)
            {
                //If the num is divisible by key,
                //then add the corressponding string mapping to current numAnsStr
                if (num % key.first == 0)
                    numAnsStr += key.second;
            }
            //Not divisible by 3 or 5, add the number
            if (numAnsStr == "")
                numAnsStr += to_string(num);
            // Append the current answer str to the ans list
            ans.push_back(numAnsStr);
        }
        return ans;
    }
};

 

以上是关于LeetCode 412. Fizz Buzz的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 412. Fizz Buzz

[LeetCode] 412. Fizz Buzz

LeetCode 412 Fizz Buzz

LeetCode 412. Fizz Buzz

LeetCode 412 Fizz Buzz[判断] HERODING的LeetCode之路

LeetCode|412. Fizz Buzz