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
    // use ctlz assembly instruction for fastest
    // could use binary search, predefined comparisons
    // binary search ?
    if (!reg) return reg;
    uint8_t pos = 0;
    if (reg >= (1u << 8)) { reg >>= 8; pos += 8; }
    if (reg >= (1u << 4)) { reg >>= 4; pos += 4; }
    if (reg >= (1u << 2)) { reg >>= 2; pos += 2; }
    if (reg >= (1u << 1)) { reg >>= 1; pos += 1; }
    return (1u << pos);

    
    // binary smear thing
    /*
    if (reg == 0) return reg;
    reg |= (reg >> 1); // upper two are set
    reg |= (reg >> 2); // upper 4 are set
    reg |= (reg >> 4); // upper 8 set
    reg |= (reg >> 8); // all set
    return (reg+1) >> 1;
    */

    /*
    if (reg == 0) return 0;
    uint32_t pos = __builtin_clz((uint32_t)reg) - 16;
    return (1u << (16-pos-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