All submissions

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
    return (n > 0) && ((n & (n - 1)) == 0) ? "YES" : "NO";
}

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

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

Solving Approach

Number n will have only single set bit if it is power of 2.    (for eg. 8 in binary  1000)

n - 1 number will have set bit in number 'n' cleared and the all the remaining right bits set. ANDing n and n -1 will result in 0, giving us if number is power of 2 or not.

Loading...

Input

8

Expected Output

YES