VOOZH about

URL: https://www.geeksforgeeks.org/dsa/toggle-bits-significant-bit/

⇱ Toggle all bits after most significant bit - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Toggle all bits after most significant bit

Last Updated : 14 Jul, 2022

Given a number, toggle all bits of it after most significant bit including most significant bit.

Examples : 

Input : 10 
Output : 5
Binary representation of 10 is 1010
After toggling we get 0101

Input : 5
Output : 2

We can toggle a bit by doing XOR of it with 1 (Note that 1 ^ 0 = 1 and 1 ^ 1 = 0). The idea is to take a number temp with only one bit set. One by one move the only set bit of temp to left and do XOR of it with n until it crosses MSB (Most Significant Bit) of n.  


Output
5

Time Complexity: O(log n)

Auxiliary Space: O(1)


The above solution can be optimized to work in O(1) time under the assumption that numbers are stored in 32 bits. 


Output
5

Time Complexity: O(1)

Auxiliary Space: O(1)


Thanks to Devanshu Agarwal for suggesting this approach.

Another Approach:

To toggle a specific bit, we can take XOR of that bit with 1.

Therefore, for an n - bit number, we can construct a binary mask of the form 1111....11111, ie, all n bits are set. This is nothing but 2n - 1.

The implementation is shown below:


Output
5

Time Complexity: O(logn)

Auxiliary Space: O(1)


 

Comment
Article Tags: