A couple of days ago I received a call from a south american country.

They are searching for web developers to work with them in some projects involving Google. They read my profile on Linkedin and decided to contact me. It was a very interesting interview due to the fact that it was focused both in evaluating my technical and logic skills.

One of the questions that were made was quite simple but I liked it:

Given a random integer ¿how would you code a function that returns the mirrored integer?

It might sound simple, but I’ve been working with PHP for years and it’s not a strong typed language so my first answer was to deal with it as a string:

<?php function mirror($number){ return strrev($number); } ?>

But then the interviewer told me that I should’t treat data as a string but as a number… ok… so I started thinking and came up with this:

<?php function mirror0($number){ $ret = 0; $prev = 0; $go = true; do{ $quotient = (int) floor($number/10); $rest = $number - ($quotient * 10); $ret = ($prev * 10) + $rest; $prev = $ret; if($quotient===0){ $go = false; } $number = $quotient; }while($go); return $ret; } ?>

He liked my answer but told me that perhaps I could do it simpler by using a logarithm… this stuck into my mind so after the call ended I wrote a piece of code:

<?php function mirror1($number){ $ret = 0; $quotient = floor($number/10); $rest = $number - ($quotient * 10); if($quotient == 0){ $ret = $rest; } else{ $ret = ($rest * (pow(10,floor(log($number,10))))) + mirror1($quotient); } return $ret; } ?>

I wrote a small benchmark code and the difference is unnoticeable.

Anyway, I’m just posting this 3 even though there might be a lot of different ways.