LeetCode每日一题——412. Fizz Buzz

原题地址:

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 list = fizzBuzz(3);
			System.out.println(list.toString());
	}

	public static  List fizzBuzz(int n) {
		List 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;
	}
}


你可能感兴趣的:(LeetCode)