What is the difference of these two?


  • 0

    First solution:

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

    Second:

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

    Seriously, is there any real difference between these two methods? Is the second better since it does less if-else judgement in execution?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.