cracking code 5.5

// write a function to determin the number of bit required to convert a->b
// a = 31 111111 , b = 14 1110, a->b 11111-> 1110
// step 1 11111-> 01111
// step 2 0111 -> 01110

// convert a to b
int convert( int a, int b )
{
int count = 0;
while( b )
{
// right shift b and a, compare each bit
// for ex the first bit of 31 is 1
// the first bit of 14 is 0, so we need to convert it
// for each bit in b, we need comparision
int digit1 = b>>1 & 1;
int digit2 = a>>1 & 1;

if( digit1 != digit2 )
{
count++;
}
}
// after all bit of b is done, if a still has some bit left, we need to convert all bits
// to be zeor, so we need to calculate how much bit left
while( a )
{
a = a>>1;
count++;
}

return count;
}

// the standard answer is super good
int bit_swap_required( int a, int b )
{
int count = 0;
// using xor, if the bit is different, then the xor of the 2 bit would be 1
for( int c = a^b; c != 0; c = c>>1 ) count++;

return count;
}

Advertisements
This entry was posted in Uncategorized and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s