31 December 2014

Quiz 72: Flip the bits

Problem:

Given a decimal number, convert it to binary. Flip the bits ie change 0 to 1 and 1 to 0 and then convert back to decimal.

Input Format: 

Decimal Number


Output Format: 

Decimal Number after making changes


Constraints: 

none

Sample Input

5

Sample Output:

2

Explanations:

5 in binary is 101, after flipping bits-010 which in decimal is 2.



Solution:

#function to convert binary to decimal
sub con {
    return unpack("N", pack("B32", substr("0" x 32 . shift, -32)));
}


chomp($n=<STDIN>);
$binary = sprintf ("%b",$n);
#print "$binary\n";
@arr=split(//,$binary);
foreach(@arr)
{
if($_ == 0)
{
$_ = 1;
}
else
{
$_ = 0;
}
}
$flip=join("",@arr);
#print "$flip\n";
$ans=con($flip);
print $ans;

Tips:

Learn conversion of Decimal to Binary and vice versa.

No comments:

Post a Comment