Keep Only the Highest Set Bit

Code

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

// Complete the function
uint16_t highest_set_bit(uint16_t reg) {
    //We use a series of shifts and ORs. Each step doubles the number of 1s we have.

    //This ensures that every $1$ now has a $1$ neighbor to its right.
    reg |= (reg>>1);

    //Since we now have blocks of two $1$s, shifting by 2 will double that block to four.
    reg |= (reg>>2);

    // This turns our 4-bit block of $1$s into an 8-bit block.
    reg |= (reg>>4);

    //This covers the entire 16-bit range.
    reg |= (reg>>8);

    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