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) {

    while (n) {
        if (n & (1U<<0) == 1)
            break;
        n = n >> 1;
    }

    if (n == 1)
        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

When we check the power of two numbers, we can see that they’re written in binary representation, in a format like 1000....00 (one followed by zeros). So the main idea in this approach is to keep removing zeros from the end of the number until we reach a one.

Once we reach a one, we check whether the number becomes equal to 1 after removing all the trailing zeros. If so, it means the given number is a power of two.

 

 

Loading...

Input

8

Expected Output

YES