Fizz Buzz
Write a program that outputs a string representation of numbers from 1 to n.
If n is a multiple of 3, print “Fizz”;
If n is a multiple of 5, output “Buzz”;
3. If n is a multiple of 3 and 5, FizzBuzz is displayed.
Examples can be found on the LeetCode website.
Source: LeetCode link: leetcode-cn.com/problems/fi… Copyright belongs to the Collar buckle network. Commercial reprint please contact official authorization, non-commercial reprint please indicate the source.
Solution 1: traversal
- First, if n is equal to 0, an empty List is returned.
- Otherwise, initialize a List as result, and then iterate over the numbers from 1 to n to judge. The judging process is as follows:
- If the current number is a multiple of both 3 and 5, add “FizzBuzz” to result;
- If the current number is a multiple of 3, add “Fizz” to result;
- If the current number is a multiple of 5, add “Buzz” to result;
- Otherwise, the current number is added to result.
- Finally, result is returned.
import java.util.ArrayList;
import java.util.List;
/ * * *@Author: ck
* @Date: 2021/9/29 7:59 下午
*/
public class LeetCode_412 {
public static List<String> fizzBuzz(int n) {
List<String> result = new ArrayList<>();
if (n == 0) {
return result;
}
for (int i = 1; i <= n; i++) {
if (i % 3= =0 && i % 5= =0) {
// Multiple of 3 and 5, output FizzBuzz
result.add("FizzBuzz");
} else if (i % 3= =0) {
// is a multiple of 3, output "Fizz"
result.add("Fizz");
} else if (i % 5= =0) {
// Is a multiple of 5, output "Buzz"
result.add("Buzz");
} else{ result.add(String.valueOf(i)); }}return result;
}
public static void main(String[] args) {
for (String str : fizzBuzz(15)) { System.out.println(str); }}}Copy the code
It is better to seek true gold from without than from within.