42
Bit Manipulation - Hacks
Bit-manipulation
Shift
Bit-shift-operators

Bit operators sometimes handy and they are quite fast too.

1 Check if a number is divisible by two or not

if(x & 1 == 0)
return True;
else
return False;


2.Code to find the Greatest Common Divisor of two numbers.

 int GCD(int a,int b)
{

while(b^=a^=b^=a%=b);

return a;

}


3.checks if non-negative integer is a power of 2 or not:

v && !(v & (v - 1))

v && (v & -v) == v


4 . Minimum and Maximum Of two Numbers x,y

max_xy = x ^ ((x ^ y) & -(x < y));    //Returns Maximum
min_xy = y ^ ((x ^ y) & -(x < y));    //Returns Minimum


5.Swap two integers a and b

a ^= b;
b ^= a;
a ^= b;

Author