Power of Two in C


Suppose we have a number n. We have to check whether the number is the power of 2 or not. So is n = 16, then the output will be true, if n = 12, it will be false.

To solve this we will use logical operations. If we see the numbers that are the power of two then in the binary representation of that number will be the MSb is 1, and all other bits are 0. So if we perform [n AND (n – 1)], this will return 0 if n is the power of 2. If we see n = 16 = 10000 in binary, (n – 1) = 15 = 01111 in binary, then 10000 AND 01111 = 00000 = 0

Example (C)

Let us see the following implementation to get a better understanding −

#include <stdio.h>
#include <math.h>
#define MAX 20
bool isPowerOfTwo(int n){
   return(n>0 && !(n & (n-1)));
}
int main() {
   printf("%s
", isPowerOfTwo(16) ? "true" : "false");    printf("%s
", isPowerOfTwo(12) ? "true" : "false");    printf("%s
", isPowerOfTwo(1) ? "true" : "false");    printf("%s
", isPowerOfTwo(32) ? "true" : "false");    printf("
"); }

Input

16
12
1
32

Output

true
false
true
true

Updated on: 28-Apr-2020

455 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements