Invert Bits Wrtie a function that gets a number and invert its bits. For example: INPUT : 10 (1010) OUTPUT : 5 (0101) Answer int invertBits(int num) { int count = 0; int invertBits = 0; while (num > 0) { if (num & 1) invertBits += 0 << count; else invertBits += 1 << count; num >>= 1; count++; } return invertBits; } INPUT : 15 (1111) OUTPUT : 0 (0000) INPUT : 24 (11000) OUTPUT : 7 (00111) INPUT : 6 (110) OUTPUT : 1 (001) Next Question>>>
I have a simple solution for this, based on the idea of 2’s complement. int reverse(int m) { int power = pow(2, log2(m) + 1); return power – m – 1; } Reply
I have a simple solution for this, based on the idea of 2’s complement.
int reverse(int m)
{
int power = pow(2, log2(m) + 1);
return power – m – 1;
}