首页 > 其他分享 >Fizz Buzz

Fizz Buzz

时间:2022-11-27 15:14:07浏览次数:28  
标签:示例 倍数 数组 Buzz answer Fizz

Fizz Buzz

一、题目描述

给定一个整数你,找到从1到n各个整数的FizzBizz表示,并用字符串数组answe(下表1开始)返回结果,其中:
answer[i] == "FizzBuzz" 同时是3和5的倍数
answer[i] == "Fizz" 如果i是3的倍数
answer[i] == "Buzz" 如果i是5的倍数
answer[i] == i 如果上述条件全不满足
示例1

输入:n = 3
输出:["1","2","Fizz"]

示例2

输入:n = 5
输出:["1","2","Fizz","4","Buzz"]

示例3

输入:n = 15
输出:["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]

二、解题思路
遍历一个数组,检查索引,判断条件,是否为3或者5的倍数,将值存在数组中并返回即可。
三、解题方法
使用数组进行条件筛选,由于数组开始下表为0,所以需要加一。
代码实现

class Solution {
    public List<String> fizzBuzz(int n) {

        String[] list = new String[n+1];

        for(int i=1; i<=n; i++){
            if( i%3==0 && i%5!=0){
                list[i] = "Fizz";
            }else if(i%5 == 0 && i%3!=0){
                list[i] = "Buzz";
            }else if(i%5 == 0 && i%3==0){
                list[i] = "FizzBuzz";
            }else{
                list[i] = i+"";
            }
            
        }

        return Arrays.asList(Arrays.copyOfRange(list,1,n+1));
    }
}

标签:示例,倍数,数组,Buzz,answer,Fizz
From: https://www.cnblogs.com/zjjtt/p/16929711.html

相关文章

  • 412. Fizz Buzz
    给你一个整数n,找出从1到n各个整数的FizzBuzz表示,并用字符串数组answer(下标从1开始)返回结果,其中:answer[i]=="FizzBuzz"如果i同时是3和5的倍数。answe......
  • LeetCode 1195. Fizz Buzz Multithreaded
    原题链接在这里:https://leetcode.com/problems/fizz-buzz-multithreaded/题目:Youhavethefourfunctions:printFizz thatprintstheword "fizz" totheconsole......