[leetcode] 412. Fizz Buzz 解題報告

題目鏈接: https://leetcode.com/problems/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"
]

思路: 很簡單的一題, 只要判斷每個數是否是3或5的倍數即可. 但是聽說還有一個follow-up, 就是不能用%和/要怎麼辦? 這種情況可以設置三個累加器, 分別用來累加統計3, 5, 15的倍數, 也就是三個累加器分別到了3, 5, 15就置0. 如此即可.

兩份代碼如下:

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

class Solution {
public:
    vector<string> fizzBuzz(int n) {
        vector<string> ans;
        int cnt3 = 0, cnt5 = 0, cnt15 = 0;
        for(int i = 1; i <= n; i++){
            cnt3++, cnt5++, cnt15++;
            if(cnt15 ==15) ans.push_back("FizzBuzz");
            else if(cnt3 == 3) ans.push_back("Fizz");
            else if(cnt5 == 5) ans.push_back("Buzz");
            else ans.push_back(to_string(i));
            if(cnt3==3) cnt3 = 0;
            if(cnt5 == 5) cnt5 = 0;
            if(cnt15 == 15) cnt15 = 0;
        }
        return ans;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章