Leetcode problem 4 - Fizz Buzz
Fizz Buzz
Given an integer n, return a string array answer (1-indexed) where:
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 (as a string) if none 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”]
/**
* @param {number} n
* @return {string[]}
*/
var fizzBuzz = function (n) {
let answers = [];
for (let i = 1; i <= n; i++) {
let by3 = i % 3 === 0;
let by5 = i % 5 === 0;
if (by3 && by5) {
answers.push("FizzBuzz");
} else if (by5) {
answers.push("Buzz");
} else if (by3) {
answers.push("Fizz");
} else {
answers.push(i.toString());
}
}
return answers;
};
The function fizzBuzz takes the input ‘n’ which is number. answers
array is empty and initialized at first which will store the results strings. A for loop used to interate from 1 to ‘n’. Inside the loop, two Boolean variables are declared: by3
and by5
These variables store the result of checking if the current number i is divisible by 3 and 5, respectively.
Time complexity : O(n) Space complexity : O(n)
Leave a comment