[leetcode] 412. Fizz Buzz 解题报告

来源:互联网 发布:网页游戏网络加速器 编辑:程序博客网 时间:2024/06/06 00:54

题目链接: 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;    }};


0 0