35. Check If a Number Is a Power of Two

Back To All Submissions
Previous Submission
Next Submission

Code

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

// Complete the function
const char* is_power_of_two(uint32_t n) {
    //Power of two: When there's only 1 '1' in the reg and the rest are 0
    //By doing n-1, we remove the lowest set bit (1100) -> (1011)
    //If we then AND n & n-1, we compare the original n and we should get 0
    //if there are no more higher bits 

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

 

 

 

Was this helpful?
Upvote
Downvote