leetcode oj java Fizz Buzz

本文介绍了一个简单的程序,该程序能够输出从1到n的数字的字符串表示形式,并使用Fizz、Buzz及FizzBuzz替代特定的倍数。文章提供了Java实现的示例代码,展示了如何通过条件判断来完成这一任务。

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

问题描述: 

    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”.

思路:这道题目非常简单,只需要判断一个数是否是3、5、15的倍数即可。但是有一个小tips, 在判断的时候下判断是否是15的倍数再判断其他的会更快一些。

代码:

import java.util.ArrayList;
import java.util.List;

/**
 * @author 作者 : xcy
 * @version 创建时间:2016年10月21日 下午9:37:54
 *          leetcode 412
 */
public class t412 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

    public static List<String> fizzBuzz(int n) {
        List<String> re = new ArrayList<String>();
        for (int i = 0; i < n; i++) {
            re.add(change(i + 1));
        }
        return re;
    }

    public static String change(int n) {
        if (n % 15 == 0) {
            return "FizzBuzz";
        }
        if (n % 5 == 0) {
            return "Buzz";
        }
        if (n % 3 == 0) {
            return "Fizz";
        }
        return n + "";
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值