All submissions

Keep Only the Highest Set Bit

Code

#include <stdio.h>\n#include <stdint.h>\n\n// Complete the function\nuint16_t highest_set_bit(uint16_t reg) {\n    // Your logic here\n    int i=0;\n    for(i=15;i>=0;i--){\n        if(reg>>i&1)\n        break;\n    }\n    reg = 0;\n    reg = reg | (1<<i);\n\n    return reg;\n}\n\nint main() {\n    uint16_t reg;\n    scanf(\"%hu\", &reg);\n\n    uint16_t result = highest_set_bit(reg);\n    printf(\"%hu\", result);\n    return 0;\n}

Solving Approach

int i=0;
    for(i=15;i>=0;i--){
        if(reg>>i&1)
        break;
    }
    reg = 0;
    reg = reg | (1<<i);

    return reg;

Step :- 1 initialize i var with 0

int i=0;

Step :- 2 iterate the loop 16 times

    for(i=15;i>=0;i--){

        if(reg>>i&1)         //  Step :- 3 checking the bit is set or clear in i position

        break;             // if i found highest i position is set break the loop

    }

    reg = 0;       // make reg zero

    reg = reg | (1<<i);    // 1 left shifting by i times

    return reg;      // returning the reg

 

Loading...

Input

44

Expected Output

32