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) {
    
    if(reg>0)
    {
       int pos=0;
       int i=0;
//until or unless reg is greater than 1<<i, we need to run the loop.As we do not know how many number of times the loop runs, hence while loop is used.
        while(reg>=(1<<i)) //this is logic to find the set bit highest position with out iterating 32 times.
       {
          if(reg&(1<<i))
          {
            pos=i;
          }
          i++;
       }
        //printf("Value of pos:%d\n",pos);
        return (1<<pos);
    }
   return 0;
}

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

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

Solving Approach

 

 

 

Loading...

Input

44

Expected Output

32