Java solution : iterative and concise with explanation


  • 0
    G

    The logic is to iterate over the numbers from 1 to n (include n).

    First, check if the number is divisible by 3 and 5, then add FizzBuzz to the ArrayList.
    Second, check if the number is divisible by 3, then add Fizz to the ArrayList.
    Third, check if the number is divisible by 3, then add Buzz to the ArrayList.
    Finally, have an else condition where the string value of the current number is added to the ArrayList.

    Complexity:
    Time : O(n)
    Space: O(n) - if you're considering the space for the ArrayList

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

Log in to reply
 

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