Power of 2 Checker
C
Easy
4 views
Problem Description
Check if a number is a power of 2 or not using only bitwise operators. (Hint: n & (n-1) == 0). Explain the logic.
Official Solution
#include <stdio.h>
/* Function to check power of 2 */
int isPowerOfTwo(unsigned int n) {
/* n must be > 0 and satisfy bitwise condition */
return (n > 0) && ((n & (n - 1)) == 0);
}
int main() {
unsigned int n;
printf("Enter a number: ");
scanf("%u", &n);
if (isPowerOfTwo(n))
printf("%u is a power of 2n", n);
else
printf("%u is NOT a power of 2n", n);
return 0;
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!