Keep Only the Highest Set Bit

Code

#include <stdio.h>
#include <stdint.h>
// You are given a 16-bit register (uint16_t).
// Your task is to:
//  + Return a value where only the highest (leftmost) set bit is retained
//  + All other bits must be cleared

uint16_t highest_set_bit(uint16_t reg){
        uint16_t u16Pos = 0; 
        for(uint16_t i =0; i<16; i++){
                if((reg >> i)&(0x0001) == 0x0001){
                    u16Pos = i; 
                }
        }
        for(uint8_t i = 0; i < u16Pos; i++){
                reg &= ~(1u<<i); 
        }
        return reg; 
}

int main(){
    uint16_t reg; 
    scanf("%hu",&reg); 
    printf("%hu",highest_set_bit(reg)); 
    return 0; 
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

44

Expected Output

32