9. Keep Only the Highest Set Bit

Discussions4
Log in to post comments and replies.
You
Loading editor...
KangajanKuganathan
#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;

    // Step 1: Smear bits to the right
    reg |= (reg >> 1);
    reg |= (reg >> 2);
    reg |= (reg >> 4);
    reg |= (reg >> 8);

    // Step 2: Subtract the (reg >> 1) value form reg   
    return reg - (reg >> 1);
}

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

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

uint16_t highest_set_bit(uint16_t reg) {

    int i;

    int j = 0;

    for (i = 15; i >= 0; i--)

    {

        if( reg & (1<<i))

        {

            reg = 0;

            reg |= (1<<i);

            return reg;

        }


 

    }

    return reg;

}


 

+2
AmitabhPathak
AmitabhPathak
Jul 19 2026

where have you used j?

 

0
GauthamShankar
GauthamShankar
Jul 29 2026

    uint16_t highest_set_bit(uint16_t reg) {

        reg|=reg>>1;

        reg|=reg>>2;

        reg|=reg>>4;

        reg|=reg>>8;

        return reg&~(reg>>1);

    }

O(1) time complexity 

+9
quoctoanahihi123
quoctoanahihi123
Jul 19 2026

#include <stdio.h>

#include <stdint.h>

 

// Complete the function

uint16_t highest_set_bit(uint16_t reg) {

    // Your logic here

    for (int i = 15; i>=0 ; i--){

        if ( reg & (1<< i)){

            return reg &= (1<<i);

        }

    }

    return 0;

}

 

int main() {

    uint16_t reg;

    scanf("%hu", &reg);

    uint16_t result = highest_set_bit(reg);

    printf("%hu", result);

    return 0;

}

0