Created
March 6, 2021 20:52
-
-
Save DvdQzd/3479461c130b1acd78b381b5ccbe681f to your computer and use it in GitHub Desktop.
LeetCode FizzBuzz Solution explained
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fizzBuzz = function(n) { | |
// Start by creating an empty list to store our result | |
var result = [] | |
// Then we iterate from 1 to the number input | |
for (let i = 1; i <= n; i++) { | |
/** | |
* This output variable is where we are | |
* storing either Fizz, Buzz or the number | |
* we are currently iterating. | |
* | |
* Notice how I am not storing anything to | |
* the result variable until the end | |
*/ | |
let output = '' | |
/** | |
* The modular operator (%) returns the remainder | |
* of a division. | |
* | |
* For example, if we need to check if a number is even, | |
* we can do that this way: | |
* | |
* const number = 4 | |
* if (number % 2 == 0) { 'number is even, because 4 / 2 = 2 and the remainder is 0' } | |
*/ | |
// So now, if the number i is multiple of 3, we add Fizz to the output. | |
if(i % 3 == 0) output += 'Fizz' | |
// If the number i is multiple of 5, we add Buzz to the output | |
if(i % 5 == 0) output += 'Buzz' | |
/** | |
* If the number is multiple of 3 AND 5, both conditions are true and | |
* both strings will concatenate, getting 'FizzBuzz' in the output variable. | |
*/ | |
/** | |
* Next, we check the output variable to see if it is empty. | |
* If it is, that means that the number i isn't multiple of 3 or 5. | |
* | |
* We can check it out with an if this way: | |
* | |
* if (output == '') { | |
* result.push(`${i}`) | |
* } else { | |
* result.push( output ) | |
* } | |
* | |
* Checking if the output variable is empty is way faster than | |
* adding a third condition to the algorithm, wich could be: | |
* | |
* if ( i % 3 !== 0 and i % 5 !== 0 ) { output = i } | |
* | |
* This looks 'fine' in this example but if in the future somebody asks | |
* to check if the number is multiple of 3, 5, 7, 9, 17, etc, | |
* you should add a new condition in this line, making it not so clean code. | |
*/ | |
/** | |
* To make the code even shorter I'm using the OR operator (||) | |
* to check if the output variable is empty. | |
* | |
* An empty string ('') if a falsy value in javascript, so | |
* that's why it pushes the number itself instead of the output variable, if it's empty. | |
*/ | |
result.push(output || `${i}`) | |
// I'm using a template string `${i}` wich is a shorter way in this case to cast the number to a String | |
} | |
// Finally, we return the result list. | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment