fizzbuzz algorithm example

Here is a simple fizzbuzz algorithm example for you to level up.

Given an integer n, return a string array answer (1-indexedwhere:

  • answer[i] == "FizzBuzz" if i is divisible by 3 and 5.
  • answer[i] == "Fizz" if i is divisible by 3.
  • answer[i] == "Buzz" if i is divisible by 5.
  • answer[i] == i if non of the above conditions are true.

Example 1:

Input: n = 3
Output: ["1","2","Fizz"]

Example 2:

Input: n = 5
Output: ["1","2","Fizz","4","Buzz"]

Example 3:

Input: n = 15
Output: ["1","2","Fizz","4","Buzz","Fizz","7","8","Fizz","Buzz","11","Fizz","13","14","FizzBuzz"]

leetcode fizzbuzz pseudocode

  • Declare an empty array to hold the final result
  • Loop through the given N from one to N.
  • of the loop is divisible by 3 and divisible by 5, push “fizzbuzz” into the result array.
  • if index of the loop is divisible by 3, push “Fizz” into the result array.
  • if index of the loop is divisible by 5, push “Fizz” into the result array.
  • Otherwise, you should push the index as a string to the result array.
  • return the result

  • Declare an empty array to hold the final result
  • var fizzBuzz = function(n) {
        var result = []
        
    
    };

  • Loop through the given N from one to N.
  • var fizzBuzz = function(n) {
        var result = []
        
        for(var i = 1; i <= n; i++){
           
        }
       
    };

  • if the index of the loop is divisible by 3 and divisible by 5, push “fizzbuzz” into the result array.
  • var fizzBuzz = function(n) {
        var result = []
        
        for(var i = 1; i <= n; i++){
            
            if(i % 3 == 0 && i % 5 == 0){
                result.push("FizzBuzz")
            }
        }
        
        return result
    };

  • if the index of the loop is divisible by 3, push “Fizz” into the result array.
  • if the index of the loop is divisible by 5, push “Fizz” into the result array.
  • Otherwise, you should push the index as a string to the result array.
  • return the result
  • var fizzBuzz = function(n) {
        var result = []
        
        for(var i = 1; i <= n; i++){
            
            if(i % 3 == 0 && i % 5 == 0){
                result.push("FizzBuzz")
            }else if(i % 3 == 0){
                result.push("Fizz")
                
            }else if(i % 5 == 0){
                result.push("Buzz")
                
            }else{
                result.push(i.toString())
            }
          
        }
        
        return result
    };

    You can try this on the leetcode platform.

    You can also view more solution here:

    You can view other solutions or level up with the link below.

    Leave a Reply

    Your email address will not be published. Required fields are marked *