Toggle Bits

Toggle All Bits from MSB - Coding Problem & Solutions
Problem - Toggle All Bits from MSB

A positive integer has been given as an input. Convert the decimal value to its binary representation. Toggle all bits of it after the most significant bit including the most significant bit. Print the positive integer value after toggling all bits.

Note:
  • If the input is non-positive or invalid, the program should print INVALID INPUT.
  • All bits from the Most Significant Bit (MSB) down to the Least Significant Bit (LSB) are inverted (0 becomes 1, and 1 becomes 0).

Example 1

Input:

10 -> Input integer
Binary: 1010
Operation: Toggle from MSB (1010 ^ 1111) = 0101

Output:
5

Solution in:

#include<stdio.h>
int main(){
    int n;
    scanf("%d", &n);
    if (n <= 0) {
        printf("INVALID INPUT");
        return 0;
    }
    int temp = n, forToggle = 0;
    while (temp > 0) {
        forToggle = (forToggle << 1) | 1;
        temp >>= 1;
    }
    int result = n ^ forToggle;
    printf("%d", result);
    return 0;
}
            

Total Pageviews