C program to check if a given number is a power of 2 in single statement

  • Write a program in C to find whether a number is power of two or not in one line.
  • How to find whether a number is power of two or not.
  • Any number who is a power of two(let it be N) have only one bit set in it’s binary representation.
    For Example: 4 = 100, 8 = 1000, 16 = 10000, 32 = 100000 etc.
  • If we subtract 1 from any power of 2 number then, the set bit becomes unset and all the bits in right side of the originally set bit becomes 1.
    For Example: 4-1 = 011, 8-1 = 0111, 16-1 = 01111, 32-1=011111
  • Now, If bitwise and(&) of N and N-1 returns ) means N is a power of 2.
    For Example, 4 & 3 = 100 & 011 = 000

C program to check whether a number is power of two using bitwise operator

C program to check if a given number is a power of 2 in single statement

#include<stdio.h>
#include<math.h>
 
int main() {
    int num;
     
    printf("Enter an integer\n");
    scanf("%d", &num);
     
    if(num && ((num & (num-1)) == 0)){
        printf("%d is power of 2", num);
    } else {
        printf("%d is not a power of 2", num);
    }
 
    return 0;
}

Output

Enter an integer
16
16 is power of 2
Enter an integer
15
16 is not a power of 2