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