Keep Only the Highest Set Bit

Code

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

uint16_t highest_set_bit(uint16_t reg) {
    for (int i = 15; i >= 0; --i) {
        uint16_t mask = (uint16_t)(1U << i);   // create mask with bit i = 1
        if (reg & mask) {
            return mask;                       // return mask that keeps only highest set bit
        }
    }
    return 0;   // reg == 0, no bits set
}

int main(void) {
    uint16_t reg;
    if (scanf("%hu", &reg) != 1) return 0;
    printf("%hu\n", highest_set_bit(reg));
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

44

Expected Output

32