Program to invert bits of a number Efficiently
Given a non-negative integer N. The task is to invert the bits of the number N and print the decimal equivalent of the number obtained after inverting the bits.
Note: Leading 0’s are not being considered.
Examples:
Input : 11 Output : 4 (11)10 = (1011)2 After inverting the bits, we get: (0100)2 = (4)10. Input : 20 Output : 11 (20)10 = (10100)2. After inverting the bits, we get: (01011)2 = (11)10.
A similar problem is already discussed in Invert actual bits of a number.
In this article, an efficient approach using bitwise operators is discussed. Below is the step by step algorithm to solve the problem:
- Calculate the total number of bits in the given number. This can be done by calculating:
X = log2N
Where N is the given number and X is the total number of bits of N.
- The next step is to generate a number with X bits and all bits set. That is, 11111….X-times. This can be done by calculating:
Step-1: M = 1 << X Step-2: M = M | (M-1)
- Where M is the required X-bit number with all bits set.
- The final step is to calculate the bit-wise XOR of M with N, which will be our answer.
Below is the implementation of the above approach:
C++
// C++ program to invert actual bits // of a number. #include <bits/stdc++.h> using namespace std; // Function to invert bits of a number int invertBits( int n) { // Calculate number of bits of N-1; int x = log2(n) ; int m = 1 << x; m = m | m - 1; n = n ^ m; return n; } // Driver code int main() { int n = 20; cout << invertBits(n); return 0; } |
Java
// Java program to invert // actual bits of a number. import java.util.*; class GFG { // Function to invert // bits of a number static int invertBits( int n) { // Calculate number of bits of N-1; int x = ( int )(Math.log(n) / Math.log( 2 )) ; int m = 1 << x; m = m | m - 1 ; n = n ^ m; return n; } // Driver code public static void main(String[] args) { int n = 20 ; System.out.print(invertBits(n)); } } // This code is contributed by Smitha |
Python3
# Python3 program to invert actual # bits of a number. import math # Function to invert bits of a number def invertBits(n): # Calculate number of bits of N-1 x = int (math.log(n, 2 )) m = 1 << x m = m | m - 1 n = n ^ m return n # Driver code n = 20 print (invertBits(n)) # This code is contributed 29AjayKumar |
C#
// C# program to invert // actual bits of a number. using System; public class GFG { // Function to invert // bits of a number static int invertBits( int n) { // Calculate number of bits of N-1; int x = ( int )(Math.Log(n) / Math.Log(2)) ; int m = 1 << x; m = m | m - 1; n = n ^ m; return n; } // Driver code public static void Main() { int n = 20; Console.Write(invertBits(n)); } } // This code is contributed by Subhadeep |
PHP
<?php // PHP program to invert actual // bits of a number. // Function to invert bits // of a number function invertBits( $n ) { // Calculate number of // bits of N-1; $x = log( $n , 2); $m = 1 << $x ; $m = $m | $m - 1; $n = $n ^ $m ; return $n ; } // Driver code $n = 20; echo (invertBits( $n )); // This code is contributed // by mits ?> |
Javascript
<script> // Javascript program to invert actual bits // of a number. // Function to invert bits of a number function invertBits(n) { // Calculate number of bits of N-1; let x = parseInt(Math.log(n) / Math.log(2)) ; let m = 1 << x; m = m | m - 1; n = n ^ m; return n; } // Driver code let n = 20; document.write(invertBits(n)); </script> |
11
Time Complexity: O(log2n)
Auxiliary Space: O(1)
Method#2: Using Bitwise NOT operator and Bitwise AND operator
Approach
1. Find the number of bits required to represent the given number.
2. Initialize a variable ‘mask’ to 2^bits-1.
3. XOR the given number with ‘mask’ and store the result in ‘result’.
4. Return ‘result’.
Algorithm
1. Initialize a variable ‘num’ with the given number.
2. Initialize a variable ‘result’ to 0.
3. Initialize a variable ‘bits’ to 0.
4. Calculate the number of bits required to represent ‘num’ and store it in ‘bits’.
5. Initialize a variable ‘mask’ to 2^bits-1.
6. XOR ‘num’ with ‘mask’ and store the result in ‘result’.
7. Return ‘result’.
Python3
def invert_bits(num): # Count number of bits count = 0 temp = num while temp > 0 : count + = 1 temp >> = 1 # Bitwise NOT of num # gives a number with all ones # up to the count of bits # Bitwise AND with num inverts the bits return (~num) & (( 1 << count) - 1 ) num = 11 print (invert_bits(num)) |
4
Time complexity: O(log n) where n is the given number.
Auxiliary Space: O(1)
METHOD 3:Using defaultdict method
APPROACH:
This program uses a defaultdict object to invert the bits of a given input number. The input number is first converted to a binary string, and then each bit of the string is toggled using a defaultdict object. Finally, the inverted bits are converted back to an integer.
ALGORITHM:
1.Convert the input number to a binary string.
2.Create a defaultdict object with int type as the default value.
3.Iterate through the binary string and toggle each bit by setting its value in the defaultdict to the opposite of its original value.
4.Convert the inverted bits back to a binary string and then to an integer using the built-in int() function.
5.Return the inverted integer.
Python3
from collections import defaultdict def invert_bits(num): # Convert the number to binary string and remove the '0b' prefix binary_str = bin (num)[ 2 :] # Create a defaultdict with int type as the default value inverted_bits = defaultdict( int ) # Iterate through the binary string and toggle each bit for i, bit in enumerate (binary_str): inverted_bits[i] = int ( not int (bit)) # Convert the inverted bits back to a binary string and then to an integer inverted_num = int (''.join( str (inverted_bits[i]) for i in range ( len (binary_str))), 2 ) return inverted_num # Example usage num = 20 inverted_num = invert_bits(num) print (inverted_num) # Output: 11 |
11
Time Complexity:
The time complexity of this program depends on the length of the binary string representation of the input number. The program iterates through the binary string once, which takes O(n) time, where n is the length of the binary string. Converting the inverted bits back to an integer using the int() function takes O(n) time as well. Therefore, the overall time complexity of the program is O(n).
Space Complexity:
The space complexity of this program is also O(n), as the defaultdict object is used to store the inverted bits, and the size of the defaultdict object is proportional to the length of the binary string.
Please Login to comment...