LeetCode-探索-初级算法-数学-1. Fizz Buzz(个人做题记录,不是习题讲解)

LeetCode-探索-初级算法-数学-1. Fizz Buzz(个人做题记录,不是习题讲解)

LeetCode探索-初级算法:https://leetcode-cn.com/explore/interview/card/top-interview-questions-easy/

  1. Fizz Buzz
  • 语言:java

  • 思路:就很简单地判断%3和%5就好了

  • 代码(3ms,81.53%):

    class Solution {
        public List<String> fizzBuzz(int n) {
            List<String> res = new ArrayList();
            for(int i = 1; i <= n; ++i){
                boolean Fizz = i % 3 == 0;
                boolean Buzz = i % 5 == 0;
                boolean FizzBuzz = Fizz&&Buzz;
                if(FizzBuzz)
                    res.add("FizzBuzz");
                else if(Fizz)
                    res.add("Fizz");
                else if(Buzz)
                    res.add("Buzz");
                else
                    res.add(""+i);
            }
            return res;
        }
    }
    
  • 参考代码(2ms):没什么太大区别

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

你可能感兴趣的:(原创,LeetCode)