Rotate image (square matrix) by 90 deg
Tue, 06 May 2025
This is pure mathematical solution to the problem. If log2(n) is integer than n is a power of 2, else not.
Method-2: Keep dividing by 2Keep dividing the number by two, i.e, do n = n/2 iteratively until n becomes 1. 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.
/** Check if a number is a power of 2 or not.
* IF n is power of 2, return 1, else return 0.
*/
int powerOfTwo(int n)
{
if(n==0) { return 0; }
while(n != 1)
{
n = n/2;
if(n%2 != 0 && n != 1){ return 0; }
}
return 1;
}
Method-3: Use Bitwise operators
This uses two facts:
N = 4, 000100 N-1 = 3, 000011 N = 16, 010000 N-1 = 15, 001111
Hence, If a number is a power of 2 then
N & (N-1)
Will be zero.
The only exception to above rule is when N is Zero. It will give zero as a power of two, which actually is not. Hence, in the check, we can see this explicitly.
/** Check if a number is a power of 2 or not.
* IF n is power of 2, return 1, else return 0.
*/
int powerOfTwo(int n)
{
return n && (!(n & (n-1)));
}
Tue, 06 May 2025
Tue, 06 May 2025
Tue, 06 May 2025
Leave a comment