美文网首页
LeetCode(Day 1)

LeetCode(Day 1)

作者: Chris_PaulCP3 | 来源:发表于2018-07-02 12:50 被阅读0次

    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”.

    一般的方法是采用取余的方法来判断i是否为3或5的倍数。但@hand515提出了一个更好的方法,即采用两个中间变量与i进行同步,判断完毕后再进行归零。

    class Solution {
        public List<String> fizzBuzz(int n) {
            List<String> out = new ArrayList<String>();
            for(int i = 1,fizz = 0,buzz = 0;i <= n;i++)
            {
                fizz++;
                buzz++;
                if(fizz == 3&& buzz == 5)
                {
                    out.add("FizzBuzz");
                    fizz = 0;
                    buzz = 0;
                }
                else if(fizz == 3)
                {
                    out.add("Fizz");
                    fizz = 0;
                }
     
                else if(buzz == 5)
                {
                    out.add("Buzz");
                    buzz = 0;
                }  
                else
                    out.add(String.valueOf(i));
            }
            return out;
        }
    }
    

    相关文章

      网友评论

          本文标题:LeetCode(Day 1)

          本文链接:https://www.haomeiwen.com/subject/qkakuftx.html