Fizz Buzz–LeetCode#412

412.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”.
Example:

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

思路:题目的意思是输入一个1-n的整数,如果是3的倍数,输出“Fizz”;如果是5的倍数,输出“Buzz”;如果既是3的倍数,也是5的倍数,输出“FizzBu​​zz”。循环遍历到n的每个数,求每个数与3或5的余数,如果余数为0,则输出“Fizz”或“Buzz”或“FizzBu​​zz”。
代码如下:

import java.util.ArrayList;
import java.util.List;
/**
 * Created by Poldi on 2017/7/7.
 */
public class FizzBuzz {
    public List<String> fizzBuzz(int n) {
        List<String> result = new ArrayList<>();
        for (int i=1;i<=n;i++){
            String temp=String.valueOf(i);
            if (i%3==0 && i%5!=0){
                temp = "Fizz";
            }else if (i%5==0 && i%3!=0){
                temp = "Buzz";
            }else if (i%3==0 && i%5==0){
                temp = "FizzBuzz";
            }
            result.add(temp);
        }
        return result;
    }
    public static void main(String[] args) {
        FizzBuzz fizzBuzz = new FizzBuzz();
        System.out.println(fizzBuzz.fizzBuzz(15));
    }
}

 

文章已创建 112

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部