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:
题解:
package com.leetcode;
import java.util.*;
public class FizzBuzz {
public static void main(String[] args) {
List<String> ans = fizzBuzz(15);
Iterator<String> it = ans.iterator();
while (it.hasNext())
System.out.println(it.next());
}
public static List<String> fizzBuzz(int n) {
List<String> ans = new ArrayList<String>();
for (int i = 1; i <= n; i++)
if (i / 3 * 3 == i && i / 5 * 5 == i)
ans.add("FizzBuzz");
else if (i / 5 * 5 == i)
ans.add("Buzz");
else if (i / 3 * 3 == i)
ans.add("Fizz");
else
ans.add(Integer.toString(i));
return ans;
}
}