So I was talking to a friend about the classic programming test question, Fizz Buzz. I’ve actually had to answer it in two interviews, which is not a lot, but some people like to pull it out. It can be whiteboarded in about 5 minutes or less and tests for some basic skills.
If you’re not familiar with the problem:
Write a function that takes an argument. If that argument is divisible by 3, output “fizz.” If it’s divisible by 5, output “buzz.” If it’s divisible by both, output “fizz buzz.”
Now the easy answer to test for divisibility is
if(x % y)===0. If the remainder of x divided by y is zero, then x is divisible by y.
But I’d been asked if there was another way to do this in one interview. PHP has a function
if(is_int(x/y)) works too.
But something occurred to me… if x is a floating point number, could you get wrong results in PHP?
With the modulus (%) solution, you can get all sorts of wrong results because the operands are converted to integers. 15.3 will pass and get a “fizz buzz” because it gets converted to 15.
If you go the
is_int() route, it checks by the variable type, not the value. If either number in that equation is a floating point number, it will produce a floating point number. Thus
if(is_int(15.0/3)) will fail. Even though the result is 5 and echoes as 5, it’s being stored in a non-integer data type.
What does that mean to Fizz Buzz? Well, with either method you have to sanitize your inputs to ensure they are integers and either throw an error/warning or skip them if they’re not, because 15.3 will pass the modulus test and 15.0 will fail the
is_int() test, meaning either can produce the wrong results.
Update: Later That Evening
Number.isInteger() function I could substitute for
3.2 % 2 and
3.3 % 2 at your own risk), but PHP would return 1. Also, since everything is a float, its