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) {
    // Your logic here
    //Integer is a power of 2 if it has only 1 set bit
    //shift through the int to count the ones
    //^ does not work as we need a loop
    //can we compare it to a certain mask and return based on their output
    //What mask should we use? 
    //what do powers of 2 look like:
    //0b0001 0b0010 0b0100 0b1000, we can compare to every single 
    //power of 2 up to 2^32 but that is very extensive to write out
    // 0b0100 - 1 = 0b0011  (0100)&(0011) = 0 what about 
    // a non power of 2, 0b0101 - 1 = 0b0100, (0101)&(0100) > 0
    // and with n and n-1 if it = 0, then we know that it is a pow of 2

    if(n == 0){
        return "NO";
    }

    if(n & (n-1)){
         return "NO";
    }
    return "YES";
}

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