当前位置 : 首页 » 文章分类 :  算法  »  LeetCode.412.Fizz Buzz

LeetCode.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"
]

解题过程

这道题很简单,就是条件判断,注意能同时被3和5整除的数别落下就行。

package _412_FizzBuzz;

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<String> fizzBuzz(int n) {
        List<String> output = new ArrayList<String>();
        for(int i=1; i<=n; i++){
            if(i%3==0){
                if(i%5==0)
                    output.add("FizzBuzz");
                else
                    output.add("Fizz");
            }else if(i%5==0){
                output.add("Buzz");
            }else{
                output.add(""+i);
            }
        }
        return output;
    }
}

public class FizzBuzz {
    public static void main(String[] args){
        Solution solution = new Solution();
        List<String> outputList = solution.fizzBuzz(15);
        System.out.println(outputList);
    }
}

GitHub代码


上一篇 LeetCode.575.Distribute Candies 分糖果

下一篇 LeetCode.682.Baseball Game

阅读
评论
259
阅读预计1分钟
创建日期 2018-01-16
修改日期 2018-01-17
类别

页面信息

location:
protocol:
host:
hostname:
origin:
pathname:
href:
document:
referrer:
navigator:
platform:
userAgent:

评论