Program to invert bits of a number Efficiently
Last Updated :
07 Mar, 2024
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++
#include <bits/stdc++.h>
using namespace std;
int invertBits( int n)
{
int x = log2(n) ;
int m = 1 << x;
m = m | m - 1;
n = n ^ m;
return n;
}
int main()
{
int n = 20;
cout << invertBits(n);
return 0;
}
|
Java
import java.util.*;
class GFG
{
static int invertBits( int n)
{
int x = ( int )(Math.log(n) /
Math.log( 2 )) ;
int m = 1 << x;
m = m | m - 1 ;
n = n ^ m;
return n;
}
public static void main(String[] args)
{
int n = 20 ;
System.out.print(invertBits(n));
}
}
|
C#
using System;
public class GFG
{
static int invertBits( int n)
{
int x = ( int )(Math.Log(n) /
Math.Log(2)) ;
int m = 1 << x;
m = m | m - 1;
n = n ^ m;
return n;
}
public static void Main()
{
int n = 20;
Console.Write(invertBits(n));
}
}
|
Javascript
<script>
function invertBits(n)
{
let x = parseInt(Math.log(n) / Math.log(2)) ;
let m = 1 << x;
m = m | m - 1;
n = n ^ m;
return n;
}
let n = 20;
document.write(invertBits(n));
</script>
|
PHP
<?php
function invertBits( $n )
{
$x = log( $n , 2);
$m = 1 << $x ;
$m = $m | $m - 1;
$n = $n ^ $m ;
return $n ;
}
$n = 20;
echo (invertBits( $n ));
?>
|
Python3
import math
def invertBits(n):
x = int (math.log(n, 2 ))
m = 1 << x
m = m | m - 1
n = n ^ m
return n
n = 20
print (invertBits(n))
|
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’.
C++
#include <iostream>
int invertBits( int num) {
int count = 0;
int temp = num;
while (temp > 0) {
count++;
temp >>= 1;
}
return (~num) & ((1 << count) - 1);
}
int main() {
int num = 11;
std::cout << invertBits(num) << std::endl;
return 0;
}
|
Java
public class InvertBits {
static int invertBits( int num)
{
int count = 0 ;
int temp = num;
while (temp > 0 ) {
count++;
temp >>= 1 ;
}
return (~num) & (( 1 << count) - 1 );
}
public static void main(String[] args)
{
int num = 11 ;
int invertedNum = invertBits(num);
System.out.println(invertedNum);
}
}
|
C#
using System;
class Program {
static int InvertBits( int num)
{
int count = 0;
int temp = num;
while (temp > 0) {
count++;
temp >>= 1;
}
return (~num) & ((1 << count) - 1);
}
static void Main()
{
int num = 11;
Console.WriteLine(InvertBits(num));
}
}
|
Javascript
function invertBits(num) {
let count = 0;
let temp = num;
while (temp > 0) {
count++;
temp >>= 1;
}
return (~num) & ((1 << count) - 1);
}
function main() {
let num = 11;
console.log(invertBits(num));
}
main();
|
Python3
def invert_bits(num):
count = 0
temp = num
while temp > 0 :
count + = 1
temp >> = 1
return (~num) & (( 1 << count) - 1 )
num = 11
print (invert_bits(num))
|
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.
C++
#include <bitset>
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int invert_bits( int num)
{
string binary_str = bitset<32>(num).to_string().substr(
bitset<32>(num).to_string().find( '1' ));
unordered_map< int , int > inverted_bits;
for ( size_t i = 0; i < binary_str.size(); ++i) {
inverted_bits[i] = 1 - (binary_str[i] - '0' );
}
int inverted_num = 0;
for ( size_t i = 0; i < binary_str.size(); ++i) {
inverted_num |= (inverted_bits[i]
<< (binary_str.size() - 1 - i));
}
return inverted_num;
}
int main()
{
int num = 20;
int inverted_num = invert_bits(num);
cout << inverted_num << endl;
return 0;
}
|
Java
import java.util.HashMap;
public class GFG {
public static int invertBits( int num)
{
String binaryStr
= Integer.toBinaryString(num).replaceFirst(
"^0+(?!$)" , "" );
HashMap<Integer, Integer> invertedBits
= new HashMap<>();
for ( int i = 0 ; i < binaryStr.length(); i++) {
int bit = binaryStr.charAt(i) == '1' ? 0 : 1 ;
invertedBits.put(i, bit);
}
int invertedNum = 0 ;
for ( int i = 0 ; i < binaryStr.length(); i++) {
int bit = invertedBits.get(i);
invertedNum
|= (bit << (binaryStr.length() - 1 - i));
}
return invertedNum;
}
public static void main(String[] args)
{
int num = 20 ;
int invertedNum = invertBits(num);
System.out.println(invertedNum);
}
}
|
C#
using System;
using System.Collections.Generic;
class MainClass {
public static void Main ( string [] args) {
int num = 20;
int invertedNum = InvertBits(num);
Console.WriteLine(invertedNum);
}
public static int InvertBits( int num) {
string binaryStr = Convert.ToString(num, 2);
int firstOneIndex = binaryStr.IndexOf( '1' );
if (firstOneIndex == -1)
return 0;
string binaryStrTrimmed = binaryStr.Substring(firstOneIndex);
Dictionary< int , int > invertedBits = new Dictionary< int , int >();
for ( int i = 0; i < binaryStrTrimmed.Length; ++i) {
invertedBits[i] = 1 - (binaryStrTrimmed[i] - '0' );
}
int invertedNum = 0;
for ( int i = 0; i < binaryStrTrimmed.Length; ++i) {
invertedNum |= (invertedBits[i] << (binaryStrTrimmed.Length - 1 - i));
}
return invertedNum;
}
}
|
Javascript
function invertBits(num) {
let binaryStr = num.toString(2).replace(/^0+(?!$)/, '' );
let invertedBits = new Map();
for (let i = 0; i < binaryStr.length; i++) {
let bit = binaryStr.charAt(i) === '1' ? 0 : 1;
invertedBits.set(i, bit);
}
let invertedNum = 0;
for (let i = 0; i < binaryStr.length; i++) {
let bit = invertedBits.get(i);
invertedNum |= bit << (binaryStr.length - 1 - i);
}
return invertedNum;
}
let num = 20;
let invertedNum = invertBits(num);
console.log(invertedNum);
|
Python3
from collections import defaultdict
def invert_bits(num):
binary_str = bin (num)[ 2 :]
inverted_bits = defaultdict( int )
for i, bit in enumerate (binary_str):
inverted_bits[i] = int ( not int (bit))
inverted_num = int (''.join( str (inverted_bits[i]) for i in range ( len (binary_str))), 2 )
return inverted_num
num = 20
inverted_num = invert_bits(num)
print (inverted_num)
|
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.
Similar Reads
Write an Efficient C Program to Reverse Bits of a Number
Given an unsigned integer, reverse all bits of it and return the number with reversed bits. Input : n = 1Output : 2147483648 Explanation : On a machine with size of unsigned bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648Output : 1 Recommended PracticeReverse BitsTry It!Method1 -
6 min read
Finding the Parity of a number Efficiently
Given an integer N. The task is to write a program to find the parity of the given number. Note: Parity of a number is used to define if the total number of set-bits(1-bit in binary representation) in a number is even or odd. If the total number of set-bits in the binary representation of a number i
8 min read
Program to toggle K-th bit of a number N
Given a number N, the task is to clear the K-th bit of this number N. If K-th bit is 0, then set it to 1 and if it is 1 then set it to 0. Examples: Input: N = 5, K = 2 Output: 7 5 is represented as 101 in binary and has its second bit 0, so toggling it will result in 111 i.e. 7. Input: N = 5, K = 1
4 min read
Bitwise OR( | ) of all even number from 1 to N
Given a number N, the task is to find the bitwise OR( | ) of all even numbers from 1 to N. Examples: Input: 2 Output: 2 Input: 10 Output: 14 Explanation: 2 | 4 | 6 | 8 | 10 = 14 Naive Approach: Initialize the result as 2.Iterate the loop from 4 to n (for all even number) and update result by finding
6 min read
Highest power of two that divides a given number
Given a number n, find the highest power of 2 that divides n.Examples: Input : n = 48 Output : 16 Highest power of 2 that divides 48 is 16.Input : n = 5 Output : 1 Highest power of 2 that divides 5 is 1. A simple solution is to try all powers of 2 one by one starting from 1, then 2, then 4 and so on
5 min read
Set all the bits in given range of a number
Given a non-negative number n and two values l and r. The problem is to set the bits in the range l to r in the binary representation of n, i.e, to unset bits from the rightmost lth bit to the rightmost r-th bit. Constraint: 1 <= l <= r <= number of bits in the binary representation of n.Ex
5 min read
Program to Convert BCD number into Decimal number
Given a BCD (Binary Coded Decimal) number, the task is to convert the BCD number into its equivalent Decimal number. Examples: Input: BCD = 100000101000 Output: 828 Explanation: Dividing the number into chunks of 4, it becomes 1000 0010 1000. Here, 1000 is equivalent to 8 and 0010 is equivalent to 2
10 min read
Reverse bits of a positive integer number in Python
Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits.Examples: Input : n = 1, bitSize=32 Output : 2147483648 On a machine with size of bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648, bitSize=32 Output : 1 We can solve this pr
4 min read
Same Number Of Set Bits As N
Given a positive integer N, find out how many positive integers strictly less than N have the same number of set bits as N. Examples: Input : 8 Output :3 Explanation: Binary representation of 8 : 1000, so number of set bits in 8 is 1. So the integers less than 8 with same number of set bits are : 4,
9 min read
Count total bits in a number
Given a positive number n, count total bit in it.Examples: Input : 13 Output : 4 Binary representation of 13 is 1101 Input : 183 Output : 8 Input : 4096 Output : 13 Method 1 (Using Log) The log2(n) logarithm in base 2 of n, which is the exponent to which 2 is raised to get n only integer and we add
7 min read