Skip to content

Instantly share code, notes, and snippets.

@jonurry
Last active July 27, 2021 12:54
Show Gist options
  • Save jonurry/c9752926d5ebd2430e9514c56cf4fdb4 to your computer and use it in GitHub Desktop.
Save jonurry/c9752926d5ebd2430e9514c56cf4fdb4 to your computer and use it in GitHub Desktop.
2.2 FizzBuzz (Eloquent JavaScript Solutions)
for (var i = 1; i <= 100; i++) {
if (i%3==0 && i%5==0)
console.log("FizzBuzz");
else if (i%3==0)
console.log("Fizz");
else if (i%5==0)
console.log("Buzz");
else
console.log(i);
}
for (var i = 1; i <= 100; i++) {
var output = "";
if (i%3==0)
output = "Fizz";
if (i%5==0)
output += ("Buzz");
console.log(output || i);
}
@jonurry
Copy link
Author

jonurry commented Feb 16, 2018

2.2. FizzBuzz

Write a program that uses console.log to print all the numbers from 1 to 100, with two exceptions. For numbers divisible by 3, print "Fizz" instead of the number, and for numbers divisible by 5 (and not 3), print "Buzz" instead.

When you have that working, modify your program to print "FizzBuzz", for numbers that are divisible by both 3 and 5 (and still print "Fizz" or "Buzz" for numbers divisible by only one of those).

(This is actually an interview question that has been claimed to weed out a significant percentage of programmer candidates. So if you solved it, your labour market value just went up.)

@jonurry
Copy link
Author

jonurry commented Feb 16, 2018

Hints

Going over the numbers is clearly a looping job, and selecting what to print is a matter of conditional execution. Remember the trick of using the remainder (%) operator for checking whether a number is divisible by another number (has a remainder of zero).

In the first version, there are three possible outcomes for every number, so you’ll have to create an if/else if/else chain.

The second version of the program has a straightforward solution and a clever one. The simple way is to add another conditional “branch” to precisely test the given condition. For the clever method, build up a string containing the word or words to output, and print either this word or the number if there is no word, potentially by making good use of the || operator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment