20.leetCode412: Fizz Buzz

来源:互联网 发布:定向数据流量 编辑:程序博客网 时间:2024/05/17 21:47

题目: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”
]
题意:输入一个整数n,输出1-n中任一字符i的字符串表示形式。若i为3的倍数但不是5的倍数,则输出Fizz;若i为5的倍数但不是3的倍数,则输出Buzz;若i既是3的倍数又是5的倍数,则输出FizzBuzz。否则,输出i.

代码

public class Solution {    public List<String> fizzBuzz(int n) {        List<String> list = new ArrayList<>();        for (int i = 1; i <= n; i++) {            if (i % 3 == 0 && i % 5 == 0) {                list.add("FizzBuzz");            } else if (i % 3 == 0) {                list.add("Fizz");            } else if (i % 5 == 0) {                list.add("Buzz");            } else {                list.add(String.valueOf(i));            }        }        return list;    }}
原创粉丝点击