Sometimes we have a simple task to do and we over-think it. Such was the case when someone asked me an interview question one time. They said, write me a quick function to prove that a provided integer ends in the number four. Instantly, without really thinking about it, bit operations popped into my head.
My first instinct was to use the comparison
if (shift(@ARGV) & 0x04) and that was wrong. Lucky for me I caught it immediately, as this will test true for a whole host of numbers which don’t end in four (e.g. 12, 13, 6, etc.), and it misses numbers which do end in four (such as 64).
The best correct answer to this question is simple as well, as the test
if ((shift(@ARGV) % 10) == 4) totally works, and it’s super easy to understand.
Here’s the full gist:
Simple is usually better, and sometimes we’re expecting complicated questions and foiled instead by a simple one. This reminds me to stop and think about the problem before answering, regardless of how complex or simple it may seem.
Also, I’m on antihistamines, so I didn’t really have much in the way of brain power to come up with anything more clever for today’s gist.
3 thoughts on “Gist of the Day: Ends in Four”
print if $ARGV =~ /4$/;
The question was originally asked in C in the context of a function taking one into parameter. You’re right though, in Perl that is the simplest answer.
Especially if you already matched the argument against a regex to check it is an integer.