2
头图

Fizz Buzz

Title description: Write a program to output a string representation of numbers from 1 to n.

  1. If n is a multiple of 3, output "Fizz";
  2. If n is a multiple of 5, output "Buzz";

    3. If n is a multiple of 3 and 5 at the same time, output "FizzBuzz".

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/fizz-buzz/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution 1: Traverse
  • First, if n is equal to 0, an empty List is returned directly.
  • Otherwise, first initialize a List as result, and then traverse the numbers from 1 to n to make a judgment. The judgment process is as follows:

    • If the current number is a multiple of 3 and 5 at the same time, 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 will be added to result .
  • Finally, return result .
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) {
                // 同时是3和5的倍数,输出 “FizzBuzz”
                result.add("FizzBuzz");
            } else if (i % 3 == 0) {
                // 是3的倍数,输出“Fizz”
                result.add("Fizz");
            } else if (i % 5 == 0) {
                // 是5的倍数,输出“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);
        }
    }
}
【Daily Message】 Seeking truth outside is not seeking truth inside.

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!