码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 412 Fizz Buzz

时间:2018-09-30 13:02:36      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:present   represent   public   puts   return   output   lis   turn   arraylist   

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

 1 public List<String> fizzBuzz(int n) {
 2         List<String> result = new ArrayList<String>();
 3         
 4         if (n <= 0) {
 5             return result;
 6         }
 7         
 8         for (int i = 1; i <= n; i++) {
 9             if (i % 3 == 0 && i % 5 == 0) {
10                 result.add("FizzBuzz");
11             } else if (i % 3 == 0) {
12                 result.add("Fizz");
13             } else if (i % 5 == 0) {
14                 result.add("Buzz");
15             } else {
16                 result.add(String.valueOf(i)); //注意要把int转化为string在add到arraylist里
17             }
18         }
19         
20         return result;
21     }

 


 

LeetCode 412 Fizz Buzz

标签:present   represent   public   puts   return   output   lis   turn   arraylist   

原文地址:https://www.cnblogs.com/jessie2009/p/9728728.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!