Keep Only the Highest Set Bit

Code

#include <stdio.h>
#include <stdint.h>

/******************************************************************************

Welcome to GDB Online.
GDB online is an online compiler and debugger tool for C, C++, Python, Java, PHP, Ruby, Perl,
C#, OCaml, VB, Swift, Pascal, Fortran, Haskell, Objective-C, Assembly, HTML, CSS, JS, SQLite, Prolog.
Code, Compile, Run and Debug online from anywhere in world.

*******************************************************************************/
#include <stdio.h>
#include <stdint.h>


uint16_t highest_set_bit(uint16_t reg) {
    
    int highest_set_bit_pos = 0;
       
       for(int i = 0; i<16; i++)
       {
           int num=reg;
           
          if((num&(1<<i))>=1)
          {
              highest_set_bit_pos = i;
          }
              
       }
       
       int result = 0;
       
       if(reg!=0)
       result = 1<<highest_set_bit_pos;
       
       return result;
    
}

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

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

44

Expected Output

32