Keep Only the Highest Set Bit

Code

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

// Complete the function
uint16_t highest_set_bit(uint16_t reg) {
    // Using for loop
    /*
    for (int i = 15; i >= 0; i--) {
        if (reg & (1U << i)) {
            return (1U << i);
        }
    }
    return 0; // no bits set
    */

    // Using while loop
    /* When you subtract 1 from a number:
        The lowest 1 bit becomes 0
        All bits to the right of it become 1
    */
    /*
    if (reg == 0) return 0;
    
    // Keep clearing the lowest set bit until only one remains
    while (reg & (reg - 1)) {
        reg &= (reg - 1);  // Clears the lowest set bit
    }
    return reg;
    */

    // bit propagation trick
    /*
    This method works in two phases:
        Propagate the highest bit to all lower positions(We repeatedly right-shift and OR to fill all lower bits with 1s.)
        Isolate just the highest bit
    */
    reg |= (reg >> 1);
    reg |= (reg >> 2);
    reg |= (reg >> 4); // covers upto 8 bits
    reg |= (reg >> 8); // covers upto 16 bits
    // Now all bits from highest to lowest are set
    // Isolate the highest bit
    return reg - (reg >> 1);
}

int main() {
    uint16_t reg;
    scanf("%hu", &reg);

    uint16_t result = highest_set_bit(reg);
    printf("%hu", result);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

44

Expected Output

32