[leetcode] 412. Fizz Buzz 解题报告

本文提供了一种解决 LeetCode 上 Fizz Buzz 问题的方法,包括两种不同的实现方式:一种使用取模运算符来判断数字是否为 3 或 5 的倍数;另一种则采用计数器的方法来避免使用取模和除法运算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值