Booking.com interview question

Convert number above in hexadecimal 312312 Ex. 255 -> FF 254 -> 254 div 16 = 14, int(254/16) = 15. -> F, E Later I found the detailed Division-remainder in source base http://en.wikipedia.org/wiki/Hexadecimal#Division-remainder_in_source_base

Interview Answers

Anonymous

6 Feb 2015

#*************************************************************************** # Creator: Zoran Hristov 03-02-2015 # # NAME: # convertDecToHex # # # PARAMETERS: # $decimal - decimal input # # RETURNS: # $rez - hexadecimal representation of the decimal input #*************************************************************************** sub convertDecToHex { my $decimal = $_[0]; my %conversionHash; $conversionHash{0} = '0'; $conversionHash{1} = '1'; $conversionHash{2} = '2'; $conversionHash{3} = '3'; $conversionHash{4} = '4'; $conversionHash{5} = '5'; $conversionHash{6} = '6'; $conversionHash{7} = '7'; $conversionHash{8} = '8'; $conversionHash{9} = '9'; $conversionHash{10} = 'A'; $conversionHash{11} = 'B'; $conversionHash{12} = 'C'; $conversionHash{13} = 'D'; $conversionHash{14} = 'E'; $conversionHash{15} = 'F'; my $decimali = $decimal; my $rez; my $rem = 1; while ( $decimal ne 0 ) { print " curent print reminder decimal \n"; $rem = $decimal % 16; print "curent devision returns $rez\n"; my $ind = $decimal - $rem; if ( $ind = 0 ) { $rez = $conversionHash{$rem} ; } else { print "For curent decimal $decimal we will transalte to $conversionHash{$rem}\n"; $decimal = ( $decimal - $rem ) / 16 ; $rez = $conversionHash{$rem} . $rez; } } print "\n Input decimal value $decimali was translated in hex reresented by: $rez \n"; } # end of sub convertDecToHex

Anonymous

21 Sept 2015

my @digits = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F); my $num = 312312; { my $out = ""; use integer; while($num > 16) { $m = $num % 16; $num = $num / 16; $out = $digits[$m] . $out; } print "$num$out\n"; }

Anonymous

13 June 2016

That's more perlish, universal approach :X perl -e '($n,$b)=@ARGV;@m=(0..9,"A".."F");$o="";while($n>0){$r=$n%$b;$n=int$n/$b;$o="$m[$r]$o"};print $o' 256 16