• 412. Fizz Buzz


    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:

    n = 15,
    
    Return:
    [
        "1",
        "2",
        "Fizz",
        "4",
        "Buzz",
        "Fizz",
        "7",
        "8",
        "Fizz",
        "Buzz",
        "11",
        "Fizz",
        "13",
        "14",
        "FizzBuzz"
    ]
    大致意思是输出一1-n的数其中3的倍数用fizz代替,5的倍数用buzz代替,15的倍数用FizzBuzz代替
    循环即可
    public List<String> fizzBuzz(int n) {
            List<String> result = new ArrayList<String>();
            for(int i=1;i<=n;i++)
            {
                if(i%3==0)
                {
                    if(i%15==0)
                    {
                        result.add("FizzBuzz");
                    }
                    else
                    {
                         result.add("Fizz");
                    }
                }
                else if(i%5==0)
                {
                    result.add("Buzz");
                }
                else
                {
                    result.add(String.valueOf(i));
                }
            }
            return result;
        }

    还有一种思路,考虑到取余的效率比较低,可以维护两个变量,一个到了3输出fizz然后归0,一个到了5输出buzz然后归0。如果同时到了3和5则输出FizzBuzz,代码很简单不写了

  • 相关阅读:
    奇迹银桥「1」
    20190729-“退役”专场
    20190727-只是睡着了
    $mathcal{Miemeng}$的病态码风计划
    20190725-Silly
    作业-[luogu4396][AHOI2013]-莫队
    数学网学笔记
    20190722-Moni和Boly的故事
    数学学习笔记
    20190719-FirstZero
  • 原文地址:https://www.cnblogs.com/icysnow/p/8206544.html
Copyright © 2020-2023  润新知