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 reg;  //This is much better error handling.
}
    uint32_t n = 0;
  
    while(reg!= 0)
    {
        reg = reg & (~(1<<n));
        n++;
    }
  
    reg = reg | (1<<(n-1));  //Had to do n-1 since n++ increases the index to one more than the reqd value of n.
    return reg;
}

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

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


//There could be multiple ways to solve this question
//While approach is there
//But there could be a simpler way to do that as well.


//Another way to do:
/*

uint16_t highest_set_bit(uint16_t reg) {
  if (reg == 0) return 0;

    uint16_t result = 1U << 15; // find the highest set bit.
    while ((reg & result) == 0) {
        result >>= 1;
    }

    return result;
}
*/

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

44

Expected Output

32