LeetCode每日一题——412. Fizz Buzz

来源:互联网 发布:网络大电影项目策划案 编辑:程序博客网 时间:2024/04/29 09:23

原题地址:

https://leetcode.com/problems/fizz-buzz/

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

举例

n = 15,Return:[    "1",    "2",    "Fizz",    "4",    "Buzz",    "Fizz",    "7",    "8",    "Fizz",    "Buzz",    "11",    "Fizz",    "13",    "14",    "FizzBuzz"]
解题思路

从0到n循环输出,通过ifelse判断并输出相应语句。


作答

public class Fizz {public static void main(String[] args) {List<String> list = fizzBuzz(3);System.out.println(list.toString());}public static  List<String> fizzBuzz(int n) {List<String> temp = new ArrayList<>();for (int i = 1; i <= n; i++) {if (i%5 == 0 && i%3 == 0) {temp.add("FizzBuzz");} else if (i%5 == 0) {temp.add("Buzz");} else if (i%3 == 0) {temp.add("Fizz");} else {temp.add(i+"");}}return temp;}}


1 0
原创粉丝点击