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
    int high =0, cur = 0,count=16;
    if (reg>0){
        while(count!=0){
            if(reg & (1<<cur))
                high = cur;
            cur++;
            count--;
        }  
        reg &= 0;
        reg |= (1<<high);  
    }

    return reg;
}

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

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

Solving Approach

The goal of the function highest_set_bit is to find the most significant bit (MSB) that is set to 1 in the given 16-bit number and return a number with only that bit set.

Initialization: 

  • Variables high (to store the index of the highest set bit) and cur (current bit index) are declared.
  • count is set to 16, since we are dealing with a 16-bit number.

Bit Scanning:

  • Loop through all 16 bit positions using cur.
  • For each position, check if the corresponding bit in reg is set using (reg & (1 << cur)). If set, update high to the current position.
  • At the end of the loop, high holds the position of the highest set bit.

Construct Result: 

  • Clear reg by setting it to 0.
  • Set only the highest bit found by doing reg |= (1 << high).

Return: The function returns the modified reg with only the highest set bit preserved.

Example:

If reg = 42 (101010 in binary), the highest set bit is at position 5 (zero-based). The result will be 32 (100000 in binary).,

 

 

Loading...

Input

44

Expected Output

32