LeetCode:Fizz Buzz

好久不见. 提交于 2019-12-05 04:12:40

1、题目名称

Fizz Buzz(Fizz Buzz 游戏)

2、题目地址

https://leetcode.com/problems/fizz-buzz/

3、题目内容

英文:

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输出到n,但遇到3的倍数时输出Fizz,遇到5的倍数时输出Buzz,遇到3和5的倍数时输出FizzBuzz

4、解题方法

FizzBuzz游戏可参考维基百科说明页面:

https://en.wikipedia.org/wiki/Fizz_buzz

这个游戏最初被设计出来的目的是让小孩学习除法。

解题Java代码如下:

import java.util.Arrays;
import java.util.List;

/**
 * LeetCode 412 - Fizz Buzz
 * @文件名称 Solution.java
 * @文件作者 Tsybius2014
 * @创建时间 2016年11月23日 下午17:17:05
 */
public class Solution {
    
    /**
     * Fizz Buzz 游戏
     * @param n
     * @return
     */
    public List<String> fizzBuzz(int n) {
        String[] array = new String[n]; 
        for (int i = 1; i <= n; i++) {
            if (i % 15 == 0) {
                array[i - 1] = "FizzBuzz";
            }
            else if (i % 3 == 0) {
                array[i - 1] = "Fizz";
            }
            else if (i % 5 == 0) {
                array[i - 1] = "Buzz";
            }
            else {
                array[i - 1] = String.valueOf(i);
            }
        }
        return Arrays.asList(array);
    }
}

以下代码也可AC:

import java.util.Arrays;
import java.util.List;

/**
 * LeetCode 412 - Fizz Buzz
 * @文件名称 Solution.java
 * @文件作者 Tsybius2014
 * @创建时间 2016年11月23日 下午17:17:05
 */
public class Solution {
    
    /**
     * Fizz Buzz 游戏
     * @param n
     * @return
     */
    public List<String> fizzBuzz(int n) {
        String[] array = new String[n]; 
        String item = "";
        for (int i = 1; i <= n; i++) {
            item = "";
            if (i % 3 == 0) {
                item += "Fizz";
            }
            if (i % 5 == 0) {
                item += "Buzz";
            }
            if (item.isEmpty()) {
                item += String.valueOf(i);
            }
            array[i - 1] = item;
        }
        return Arrays.asList(array);
    }
}

END

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!