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
    uint16_t reg_highestval = 1U<<15; // Set all the bits 
    if (reg == 0)return 0;
    while((reg & reg_highestval)==0) // To make sure the other bits are cleared
    {
        reg_highestval>>=1; // Keep right shifting 1 to place it in the highest bit
    }
    return reg_highestval;
}

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

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

Solving Approach

Using while loop and setting all the bits, we can perform this operation 

    uint16_t reg_highestval = 1U<<15; // To set all bits
    if (reg == 0)return 0;
    while((reg & reg_highestval)==0) // To make sure the other bits are cleared
    {
        reg_highestval>>=1; // Keep right shifting 1 to place it in the highest bit
    }
    return reg_highestval;

 

Upvote
Downvote
Loading...

Input

44

Expected Output

32