Write one line C function to find whether a no is power of two | GeeksforGeeks
Write one line C function to find whether a no is power of two 1.
1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2.
2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2
Read full article from Write one line C function to find whether a no is power of two | GeeksforGeeks
Write one line C function to find whether a no is power of two 1.
If we subtract a power of 2 numbers by 1 then all unset bits after the only set bit become set; and the set bit become unset.
So, if a number n is a power of 2 then bitwise & of n and n-1 will be zero.
The expression n&(n-1) will not work when n is 0. To handle this case also, our expression will become n& (!n&(n-1)) bool
isPowerOfTwo (
int
x)
{
return
x && (!(x&(x-1)));
}
1. A simple method for this is to simply take the log of the number on base 2 and if you get an integer then number is power of 2.
2. Another solution is to keep dividing the number by two, i.e, do n = n/2 iteratively. In any iteration, if n%2 becomes non-zero and n is not 1 then n is not a power of 2. If n becomes 1 then it is a power of 2
bool
isPowerOfTwo(
int
n)
{
if
(n == 0)
return
0;
while
(n != 1)
{
if
(n%2 != 0)
return
0;
n = n/2;
}
return
1;
}
3. All power of two numbers have only one bit set. So count the no. of set bits and if you get 1 then number is a power of 2.
http://www.geeksforgeeks.org/count-set-bits-in-an-integer/
int
countSetBits(
int
n)
{
unsigned
int
count = 0;
while
(n)
{
n &= (n-1) ;
count++;
}
return
count;
}