Check If a Number Is a Power of Two

Code

#include <stdio.h>
#include <stdint.h>

// Complete the function
const char* is_power_of_two(uint32_t n) {
    // Your logic here
    if((n!=0) && (n&(n-1))==0){
        return "YES";
    }
    return "NO";
}

int main() {
    uint32_t n;
    scanf("%u", &n);

    const char* result = is_power_of_two(n);
    printf("%s", result);
    return 0;
}

Solving Approach

A power of 2 will only have one set bit. So knowing this, if we decrement the power of 2 by 1, all the bits before this will become 1. If we bitwise AND both n and n-1 it should result in 0.

 

 

Upvote
Downvote
Loading...

Input

8

Expected Output

YES