- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# 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\n", isPowerOfTwo(16) ? "true" : "false"); printf("%s\n", isPowerOfTwo(12) ? "true" : "false"); printf("%s\n", isPowerOfTwo(1) ? "true" : "false"); printf("%s\n", isPowerOfTwo(32) ? "true" : "false"); printf("\n"); }

## Input

16 12 1 32

## Output

true false true true

- Related Questions & Answers
- Check for Power of two in JavaScript
- Power of Four in C++
- Find power of power under mod of a prime in C++
- C++ Program to find whether a number is the power of two?
- Reordered Power of 2 in C++
- How to generate a power sequence of two in R?
- Power Function in C/C++
- Count the nodes in the given tree whose weight is a power of two in C++
- Check if bitwise AND of any subset is power of two in Python
- Power in Mathematics in C++
- Python Program to find whether a no is power of two
- Program to check a number is power of two or not in Python
- Find power of a number using recursion in C#
- Python Program to find whether a no is the power of two
- How to calculate power of three using C#?

Advertisements