All submissions

Keep Only the Highest Set Bit

Code

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

// Complete the function
uint16_t highest_set_bit(uint16_t reg) {
    // Your logic here
    if(reg == 0)
        return 0;
    //propagate highest bits to the right
    reg |= (reg>>1);
    reg |= (reg>>2);
    reg |= (reg>>4);
    reg |= (reg>>8);
    //isolate the highest set 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

  1. Propagate the highest set bit by OR-ing the number with progressively right-shifted versions of itself (x |= x >> 1, x |= x >> 2, etc.).
  2. Create a mask by shifting the propagated result right by 1 and inverting it (~(x >> 1)).
  3. Isolate the highest bit by AND-ing the propagated value with the mask (x & ~(x >> 1)).

 

 

Loading...

Input

44

Expected Output

32