![]() |
VOOZH | about |
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
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:
Below is the implementation of the above approach:
15
Time Complexity: O(1)
Auxiliary Space: O(1)