FizzBuzz Java Solution O(n)


  • 0
    S
    class Solution {
        public List<String> fizzBuzz(int n) {
            
            //Creating a list to hold the final values
            List<String> list = new ArrayList<String>();
    
            // Loop through all the numbers linearly
            for(int i = 1; i <=n; i++) {
                String stringRep = "";
                // If multiple of either 3 or 5, go ahead and add Fizz/Buzz/FizzBuzz
                if(i % 3 == 0 || i % 5 == 0) {
                    if(i % 3 == 0) {
                        stringRep = stringRep + "Fizz";
                    }
                    if(i % 5 == 0) {
                        stringRep = stringRep + "Buzz";
                    }
                } 
                // Else just convert to string
                else {
                    stringRep = String.valueOf(i);
                }
                // Append to final list
                list.add(stringRep);
            }
            return list;
        }
    }
    

Log in to reply
 

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