VOOZH about

URL: https://www.geeksforgeeks.org/dsa/toggle-bits-number-expect-first-last-bits/

⇱ Toggle bits of a number except first and last bits - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Toggle bits of a number except first and last bits

Last Updated : 3 Aug, 2022

Given a number, the task is to toggle bits of the number except the first and the last bit.
Examples: 

Input : 10
Output : 12
Binary representation:- 1 0 1 0
After toggling first and last : 1 1 0 0

Input : 9
Output : 15
Binary representation : 1 0 0 1
After toggling first and last : 1 1 1 1

Prerequisite: Find most significant set bit of a number

  1. Generate a number that contains the middle bit as a set. We need to change all middle bits to 1 and keep corner bits as 
  2. The answer is XOR of generated number and original number. Note that XOR of 1 with a number toggles the number.

Output
15

Time Complexity: O(log2n), where n is the given number 
Auxiliary Space: O(1)
 

Another Approach: Using bit mask
The idea to solve this problem is that we can use XOR of a specific bit with 1 to toggle the specific bit. Therefore, for an n - bit number, we can construct a bit mask of the form 0111....11110, ie, an n - bit number, where all bits are set except the first and last bit. Therefore, for a number that is greater than or equal to 4, the bit mask is equal to 2n - 2. (n can be calculated using log2number)  (For numbers less than 4, there are no middle bits, therefore, the number will not be changed).

Approach:

  1. Calculate the bit mask = 2 log2number - 2
  2. Perform the XOR of the number and the mask.

Below is the implementation of the above approach:


Output
15

Time Complexity: O(1)
Auxiliary Space: O(1)

Comment
Article Tags:
Article Tags: