How to toggle all bits after MSB
Problem statement
Given a number n, toggle all bits after the most significant bit including the most significant bit.
Example 1
- Input:
n=11 - Output:
4
Example 2
- Input:
n=15 - Output:
0
Solution
To toggle a specific bit, we take the XOR of the bit with 1.
We can achieve this two ways:
- By using a bit mask.
- By looping via bit by bit until the MSB is reached.
Here, we discuss the first approach by using a bit mask.
The steps of the first approach are as follows:
- Find the number of bits of the number. The bit mask is 2n - 1. We can find the number of bits of the number by taking the log of the number and adding one to it.
- Do a bitwise XOR with the bit mask and the number.
Let’s understand this with the help of an example.
Consider n=11. The binary representation of 11 is 1011, that is, 4 bits are used to represent 11.
The bit mask is 24 - 1, that is, 15.
- 11:
1011 - 15:
1111 - 11 XOR 15:
0100
Hence, the output is 4.
Code
#include<bits/stdc++.h>using namespace std;int toggle(int num) {int n = (int)log2(num) + 1;int mask = pow(2, n) - 1;return num ^ mask;}int main(){int num = 11;cout << toggle(num);}
Explanation
-
Line 5: The
togglefunction is initialized. -
Line 6: We get the
noOfBitsby taking the log base 2 of thenumand adding1to it. -
Line 7: We get the bit mask by taking
2raised to the power ofnoOfBitsand then subtracting by1 -
Lines 11–15: We initialize the
numand print the resulting output.