To describe the FizzBuzz problem — one of the famous interview problems — in brief:
You have to write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number, and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
How would you approach when someone asks you a solution for the problem. Based on what you have learnt so far; if possible, surprise us with a cool answer! Use whatever programming language, you are comfortable with :D
Psst, this can also be an intro for us who are new to the syntax of your super cool language 👍🏻
Ruby:
(1..100).each do |i| # Built-in support for ranges, iterator blocks
str = ''
str << 'Fizz' if i % 3 == 0 # Mutable strings, postfix conditionals
str << 'Buzz' if i % 5 == 0
puts str.empty? ? i : str
end
Great question! FizzBuzz is indeed one of the most well known screening questions asked in interviews. I remember coming across a cool Python solution that got it done using generators, without resorting to any modulo logic. Here's how you'd do it in JavaScript, using generators. :-)
(function () {
function* yieldFizzAt3() {
while (true) {
yield '';
yield '';
yield 'Fizz';
}
};
function* yieldBuzzAt5() {
while (true) {
yield '';
yield '';
yield '';
yield '';
yield 'Buzz';
}
};
var fizz = yieldFizzAt3();
var buzz = yieldBuzzAt5();
for (var i = 1; i < 101; i++) {
var fizzBuzz = fizz.next().value + buzz.next().value;
console.log(fizzBuzz ? fizzBuzz : i);
}
})();
for(int i = 0; i <= 100; i++){
Console.WriteLine(i % 3 == 0 && i % 5 == 0 ? "FizzBuzz" : i % 3 == 0 ? "Fizz" : i % 5 == 0 ? "Buzz" : i.ToString());
}
That's how I resolved it during an interview, using C#
well i would go for a nested if
if number modulo 3 and number modulo 5
write FizzBuzz
else if number modulo 3
write Fizz
else if number modulo 5
write Buzz
else
write number
so if we wanna reduce the amount of operations by two we could assign
mod3 = number modulo 3
mod5 = number modulo 5
if mod3 and mod5
.....
or did i missunderstand the problem ? or do you want examples of different languages ? ;D ....
Emil Moe
Senior Data Engineer
public function isFizz(number) { return number % 3; } public function isBuzz(number) { return number % 5; } ... if (isFizz(number)) echo 'Fizz'; if (isBuzz(number)) echo 'Buzz'; if (!isFizz(number) || !isBuzz(number)) echo number; echo '<br>';