6

LeetCode-412-Fizz Buzz

 2 years ago
source link: https://segmentfault.com/a/1190000040769092
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

LeetCode-412-Fizz Buzz

发布于 10 月 3 日

Fizz Buzz

题目描述:写一个程序,输出从 1 到 n 数字的字符串表示。

  1. 如果 n 是3的倍数,输出“Fizz”;
  2. 如果 n 是5的倍数,输出“Buzz”;

    3.如果 n 同时是3和5的倍数,输出 “FizzBuzz”。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/probl...
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:遍历
  • 首先,如果n等于0,则直接返回空List。
  • 否则,先初始化一个List为result,然后遍历从1到n的数字,进行判断,判断过程如下:

    • 如果当前数字同时是3和5的倍数,则将 “FizzBuzz”添加到result中;
    • 如果当前数字是3的倍数,则将“Fizz”添加到result中;
    • 如果当前数字是5的倍数,则将“Buzz”添加到result中;
    • 否则,将将当前数字添加到result中。
  • 最后,返回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);
        }
    }
}

【每日寄语】 外求真金莫于内求真心。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK