Keep Only the Highest Set Bit

Code

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

#define testbit(reg, pos) (reg & (1<<pos))
#define clearbit(reg, pos) (reg &= ~(1<<pos))

// Complete the function
uint16_t highest_set_bit(uint16_t reg) {
    // Your logic here
    int high_bit_pos = -1;
    int pos;
    for (pos =0; pos < 16; pos++) {
        if(testbit(reg, pos)) {
            high_bit_pos = pos;
            //printf("high_bit_pos: %d\n",high_bit_pos);     
        }
    }

    for (pos =0; pos < 16; pos++) {
        if (pos == high_bit_pos) {
            //printf("Ignore highest pos: %d\n", high_bit_pos);
            continue;
        }
        if(testbit(reg, pos)) {
            clearbit(reg, pos);
        }
    }
    return reg;
}

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