The Wayback Machine - https://web.archive.org/web/20240909234323/https://www.geeksforgeeks.org/invert-actual-bits-number/
Open In App

Invert actual bits of a number

Last Updated : 29 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Basic
63.73%
1.9K

Given a non-negative integer n. The problem is to invert the bits of n and print the number obtained after inverting the bits. Note that the actual binary representation of the number is being considered for inverting the bits, no leading 0’s are being considered. 

Examples: 

Input : 11
Output : 4
(11)10 = (1011)[2]
After inverting the bits, we get:
(0100)2 = (4)10.
Input : 10
Output : 5
(10)10 = (1010)2.
After reversing the bits we get:
(0101)2 = (101)2
= (5)10.

Method 1 (Using bitwise operators)
Prerequisite: Toggling k-th bit of a number 

C++




// CPP program to invert actual bits
// of a number.
#include <bits/stdc++.h>
using namespace std;
  
void invertBits(int num)
{
    // calculating number of bits
    // in the number
    int x = log2(num) + 1;
  
    // Inverting the bits one by one
    for (int i = 0; i < x; i++) 
       num = (num ^ (1 << i)); 
   
    cout << num;
}
  
// Driver code
int main()
{
    int num = 11; 
    invertBits(num);
    return 0;
}


Java




// Java program to invert 
// actual bits of a number.
import java.io.*;
  
class GFG
{
    static void invertBits(int num)
    {
        // calculating number of 
        // bits in the number
        int x = (int)(Math.log(num) / 
                      Math.log(2)) + 1;
      
        // Inverting the 
        // bits one by one
        for (int i = 0; i < x; i++) 
        num = (num ^ (1 << i)); 
      
        System.out.println(num);
    }
      
    // Driver code
    public static void main (String[] args) 
    {
        int num = 11; 
        invertBits(num);
    }
  
}
  
// This code is contributed
// by Anuj_67


Python3




# Python3 program to invert actual 
# bits of a number. 
import math
  
def invertBits(num): 
  
    # calculating number of bits 
    # in the number 
    x = int(math.log2(num)) + 1
  
    # Inverting the bits one by one 
    for i in range(x): 
        num = (num ^ (1 << i)) 
      
    print(num) 
  
# Driver Code
num = 11
invertBits(num) 
  
# This code is contributed 
# by Rituraj Jain


C#




// C# program to invert 
// actual bits of a number.
using System;
  
class GFG
{
    static void invertBits(int num)
    {
        // calculating number of 
        // bits in the number
        int x = (int)(Math.Log(num) / 
                       Math.Log(2)) + 1;
      
        // Inverting the 
        // bits one by one
        for (int i = 0; i < x; i++) 
        num = (num ^ (1 << i)); 
      
        Console.WriteLine(num);
    }
      
    // Driver code
    public static void Main () 
    {
        int num = 11; 
        invertBits(num);
    }
  
}
  
// This code is contributed
// by Anuj_67


Javascript




<script>
  
    // Javascript program to invert 
    // actual bits of a number.
      
    function invertBits(num)
    {
        // calculating number of 
        // bits in the number
        let x = 
        parseInt(Math.log(num) / Math.log(2), 10) + 1;
        
        // Inverting the 
        // bits one by one
        for (let i = 0; i < x; i++) 
            num = (num ^ (1 << i)); 
        
        document.write(num);
    }
      
    let num = 11; 
      invertBits(num);
  
</script>


PHP




<?php
// PHP program to invert actual bits
// of a number.
  
function invertBits( $num)
{
      
    // calculating number of bits
    // in the number
    $x = log($num) + 1;
  
    // Inverting the bits one by one
    for($i = 0; $i < $x; $i++) 
    $num = ($num ^ (1 << $i)); 
  
    echo $num;
}
  
    // Driver code
    $num = 11; 
    invertBits($num);
      
// This code is contributed by anuj_67.
?>


Output

4





Time complexity : O(log n) 
Auxiliary space : O(1)

Method 2 (Using bit-wise operators)

Think about generating a number just less than or equal to ‘n’ with all bits ‘1’ and take xor of that number with ‘n’.

Algorithm:

  1. A variable ‘x’ is initialized to 1.
  2. The function enters a while loop that continues until ‘x’ is less than or equal to the input integer (A).
  3. Inside the while loop, ‘x’ is left-shifted by 1 using the bit-wise left shift operator (<<=). This multiplies ‘x’ by 2.
  4. After the while loop, the value of ‘x’ is decremented by 1.
  5. The function returns the result of the bit-wise XOR operation between ‘x’ and the input integer (A)
  6. The final result is the bit-wise XOR of the input integer with the largest power of 2 that is less than or equal to the input integer.

Below is the implementation of the above idea:

C++




#include <bits/stdc++.h>
using namespace std;
  
class GFG {
public:
    int Opposite(int n)
    {
        int x = 1;
        while (x <= n) {
            x <<= 1;
        }
        x--;
        return (x ^ n);
    }
};
  
int main()
{
    int n = 5;
    GFG Obj = GFG();
    cout << Obj.Opposite(n);
    return 0;
}


Java




import java.util.*;
class GFG {
   public int Opposite(int n) {
       int x = 1;
       while(x <= n){
           x <<= 1;
       }
       x--;
       return (x ^ n);
   }
}
public class Main {
   public static void main(String[] args) {
       int n = 5;
       GFG Obj = new GFG();
       System.out.print(Obj.Opposite(n));
   }
}


Python3




class GFG:
    def Opposite(self, n):
        x = 1
        while x <= n:
            x <<= 1
        x -= 1
        return (x ^ n)
  
n = 5
Obj = GFG()
print(Obj.Opposite(n))


C#




using System;
  
public class GFG {
    public int Opposite(int n)
    {
        int x = 1;
        while (x <= n) {
            x <<= 1;
        }
        x--;
        return (x ^ n);
    }
}
  
class Program {
    static void Main(string[] args)
    {
        int n = 5;
        GFG Obj = new GFG();
        Console.WriteLine(Obj.Opposite(n));
    }
}


Javascript




// Javascript code addition 
  
// Creating a class name GFG 
class GFG {
      
  Opposite(n) {
    let x = 1;
        
    // Keep multiplying x by 2, until x <= n
    while (x <= n) {
      x <<= 1;
    }
        
    // decrease the value of x by 1. 
    x--;
        
    // return xor of x and n. 
    return (x ^ n);
  }
}
  
// assigning value to n
let n = 5;
  
// creating an object. 
let Obj = new GFG();
  
// calling Opposite() function from the class. 
console.log(Obj.Opposite(n));
  
// The code is contributed by Arushi Goel.


Output

2





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

Method 3 (Using Bitset) 
Here we use the flip() of bitset to invert the bits of the number, in order to avoid flipping the leading zeroes in the binary representation of the number, we have calculated the number of bits in the binary representation and flipped only the actual bits of the number. We have used to_ulong() to convert bitset to number.

C++




// CPP program to invert actual bits
// of a number.
#include <bits/stdc++.h>
using namespace std;
  
void invertBits(int num)
{
    // calculating number of bits
    // in the number
    int x = log2(num) + 1;
  
    // Considering number to be 32 bit integer;
    bitset<32> b(num);
  
    // reversing the bits one by one
    for (int i = 0; i < x; i++) 
        b.flip(i);
  
    // converting bitset to number
    cout << b.to_ulong(); 
}
  
// Driver code
int main()
{
    int num = 11; 
    invertBits(num);
    return 0;
}


Java




// Java program to invert actual 
// bits of a number.
class GFG 
{
    static void invertBits(int num)
    {
        // calculating number of 
        // bits in the number
        int x = (int)(Math.log(num) / 
                      Math.log(2)) + 1;
      
        // Inverting the bits
        // one by one
          
        for (int i = 0; i < x; i++) 
        num = (num ^ (1 << i)); 
      
        System.out.print(num);
    }
      
    // Driver code
    public static void main(String[] args)
    {
        int num = 11; 
        invertBits(num);
    }
}
  
// This code is contributed by Mukul Singh


Python 3




# Python 3 program to invert actual 
# bits of a number.
import math
  
def invertBits(num):
      
    # calculating number of 
    # bits in the number
    x = int(math.log(num, 2.0) + 1);
  
    # Inverting the bits
    # one by one
    for i in range(0, x): 
        num = (num ^ (1 << i)); 
  
    print(num);
  
# Driver code
num = 11; 
invertBits(num);
  
# This code is contributed 
# by Akanksha Rai


C#




// C# program to invert actual 
// bits of a number.
using System;
  
class GFG 
{
    static void invertBits(int num)
    {
        // calculating number of 
        // bits in the number
        int x = (int)Math.Log(num, 2) + 1;
      
        // Inverting the bits
        // one by one
        for (int i = 0; i < x; i++) 
        num = (num ^ (1 << i)); 
      
        Console.Write(num);
    }
      
    // Driver code
    static void Main()
    {
        int num = 11; 
        invertBits(num);
    }
  
}
  
// This code is contributed by Anuj_67


Javascript




<script>
    // Javascript program to invert actual bits of a number.
      
    function invertBits(num)
    {
        // calculating number of 
        // bits in the number
        let x = Math.log(num, 2) + 1;
        
        // Inverting the bits
        // one by one
        for (let i = 0; i < x; i++) 
        num = (num ^ (1 << i)); 
        
        document.write(num);
    }
      
    let num = 11; 
      invertBits(num);
  
</script>


PHP




<?php
// PHP program to invert actual 
// bits of a number. 
function invertBits($num) 
{ 
    // calculating number of 
    // bits in the number 
    $x = log($num) + 1; 
  
    // Inverting the bits 
    // one by one 
    for ($i = 0; $i < $x; $i++) 
    $num = ($num ^ (1 << $i)); 
  
        echo $num; 
} 
  
// Driver code 
$num = 11; 
invertBits($num); 
  
// This code is contributed 
// by ajit
?>


Output

4





Time complexity: O(log n) 
Auxiliary space: O(1)

Method 4 (Using bitmask):

Here, we will create a mask by setting all the bits from MSB(including MSB) and then take XOR with the original number

C++




// CPP program to invert actual bits
// of a number.
#include <bits/stdc++.h>
using namespace std;
  
void invertBits(int num)
{
    // calculating the mask
    int x = num;     // say num = 100000
      x |= x >> 1;    // 100000 | 010000 = 110000
      x |= x >> 2;    // 110000 | 001100 = 111100
      x |= x >> 4;    // 111100 | 000011 = 111111
      x |= x >> 8;    // 111111 | 000000 = 111111
      x |= x >> 16;    // 111111 | 000000 = 111111
   
    cout << (num ^ x); // 100000 | 111111 = 011111
}
  
// Driver code
int main()
{
    int num = 11; 
    invertBits(num);
    return 0;
}


Java




/*package whatever //do not write package name here */
  
import java.io.*;
  
class GFG {
  public static void invertBits(int num) {
    //base case
    if(num == 0) 
    {
      System.out.println(1);
      return;
    }
    // calculating the mask
    int x = num;     // say num = 100000
    x |= x >> 1;    // 100000 | 010000 = 110000
    x |= x >> 2;    // 110000 | 001100 = 111100
    x |= x >> 4;    // 111100 | 000011 = 111111
    x |= x >> 8;    // 111111 | 000000 = 111111
    x |= x >> 16;    // 111111 | 000000 = 111111
      
    System.out.println(num ^ x); // 100000 | 111111 = 011111
  }
  // Driver code
    public static void main(String[] args)
    {
        int num = 11; 
        invertBits(num);
    }
}
  
// This code is contributed by lapimpale@


Python3




def invertBits(num):
    # calculating the mask
    x = num
    x |= x >> 1
    x |= x >> 2
    x |= x >> 4
    x |= x >> 8
    x |= x >> 16
  
    print(num ^ x)
  
  
# Driver Code
num = 11
invertBits(num)


C#




// C# code to implement the approach
  
using System;
  
class GFG {
  
    public static void invertBits(int num)
    {
        // base case
        if (num == 0) {
            Console.WriteLine(1);
            return;
        }
        // calculating the mask
        int x = num; // say num = 100000
        x |= x >> 1; // 100000 | 010000 = 110000
        x |= x >> 2; // 110000 | 001100 = 111100
        x |= x >> 4; // 111100 | 000011 = 111111
        x |= x >> 8; // 111111 | 000000 = 111111
        x |= x >> 16; // 111111 | 000000 = 111111
  
        Console.WriteLine(num
                          ^ x); // 100000 | 111111 = 011111
    }
  
    // Driver code
    public static void Main(string[] args)
    {
        int num = 11;
        invertBits(num);
    }
}
  
// This code is contributed by phasing17


Javascript




// JavaScript program to invert actual bits
// of a number.
  
  
function invertBits(num)
{
    // calculating the mask
    let x = num;     // say num = 100000
      x |= x >> 1;    // 100000 | 010000 = 110000
      x |= x >> 2;    // 110000 | 001100 = 111100
      x |= x >> 4;    // 111100 | 000011 = 111111
      x |= x >> 8;    // 111111 | 000000 = 111111
      x |= x >> 16;    // 111111 | 000000 = 111111
   
    console.log(num ^ x); // 100000 | 111111 = 011111
}
  
// Driver code
let num = 11; 
invertBits(num);
  
  
// This code is contributed by phasing17


Output

4





Time complexity: O(1) 
Auxiliary space: O(1)

Method 5 (Extracting only the relevant bits using log and XOR)

The inverted number can be efficiently obtained by:

1. Getting the number of bits using log2

2. Taking XOR of the number and 2 numOfBits – 1 

C++




// CPP program to invert actual bits
// of a number.
#include <bits/stdc++.h>
using namespace std;
  
void invertBits(int num)
{
   // Find number of bits in the given integer
   int numOfBits = (int)log2(num) + 1;
  
   // invert the number by taking 
   // xor of n and (2 raised to numOfBits) - 1
   cout <<  (((1 << numOfBits) - 1) ^ num);
}
  
// Driver code
int main()
{
    int num = 11; 
    //Function Call
    invertBits(num);
    return 0;
}
  
//This code is contributed by phasing17


Java




// Java program to invert actual bits
// of a number.
import java.io.*;
  
class GFG {
static void invertBits(int num)
{
// Find number of bits in the given integer
int numOfBits = (int)(Math.log(num) / Math.log(2)) + 1; 
      // invert the number by taking 
    // xor of n and (2 raised to numOfBits) - 1
    System.out.println(((1 << numOfBits) - 1) ^ num);
}
  
// Driver code
public static void main(String[] args)
{
    int num = 11;
    //Function Call
    invertBits(num);
}
}


Python




# Python program to invert actual bits
# of a number.
  
def invertBits(num):
    # Find number of bits in the given integer
    numOfBits = num.bit_length()
  
    # Invert the number by taking
    # xor of n and (2 raised to numOfBits) - 1
    print(((1 << numOfBits) - 1) ^ num)
  
# Driver code
num = 11
# Function Call
invertBits(num)


C#




// C# program to invert actual bits
// of a number.
  
using System;
  
class GFG
{
    static void invertBits(int num)
    {
        // Find number of bits in the given integer
        int numOfBits = (int)(Math.Log(num) / Math.Log(2)) + 1;
        // invert the number by taking 
        // xor of n and (2 raised to numOfBits) - 1
        Console.WriteLine(((1 << numOfBits) - 1) ^ num);
    }
  
    // Driver code
    public static void Main(string[] args)
    {
        int num = 11;
        // Function Call
        invertBits(num);
    }
}
  
  
// contributed by phasing17


Javascript




// JavaScript program to invert actual bits
// of a number.
  
function invertBits(num) {
  // Find number of bits in the given integer
  let numOfBits = Math.floor(Math.log2(num)) + 1;
    
  // Invert the number by taking 
  // xor of n and (2 raised to numOfBits) - 1
  console.log(((1 << numOfBits) - 1) ^ num);
}
  
// Driver code
let num = 11;
// Function Call
invertBits(num);


Output

4





Time complexity: O(1)
Auxiliary space: O(1)



Similar Reads

Reverse actual bits of the given number
Given a non-negative integer n. The problem is to reverse the bits of n and print the number obtained after reversing the bits. Note that the actual binary representation of the number is being considered for reversing the bits, no leadings 0's are being considered.Examples : Input : 11Output : 13Explanation: (11)10 = (1011)2.After reversing the bi
15+ min read
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 : 11Output : 4(11)10 = (1011)2After inverting the bits, we get:(0100)2 = (4)10.Input : 20Output : 11(20)10 = (10100)2.After invert
11 min read
Different ways to Invert the Binary bits in Python
We know how binary value for numbers look like. For example, the binary value for 10 (Number Ten) is 1010 (binary value). Sometimes it is required to inverse the bits i.e., 0's to 1's ( zeros to ones) and 1's to 0's (ones to zeros). Here are there few ways by which we can inverse the bits in Python. 1) Using Loops: By iterating each and every bit w
3 min read
Check if actual binary representation of a number is palindrome
Given a non-negative integer n. The problem is to check if binary representation of n is palindrome or not. Note that the actual binary representation of the number is being considered for palindrome checking, no leading 0’s are being considered. Examples : Input : 9 Output : Yes (9)10 = (1001)2 Input : 10 Output : No (10)10 = (1010)2Recommended Pr
6 min read
Toggle bits of a number except first and last bits
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 Gene
8 min read
Check if bits of a number has count of consecutive set bits in increasing order
Given a integer n &gt; 0, the task is to find whether in the bit pattern of integer count of continuous 1's are in increasing from left to right. Examples : Input:19 Output:Yes Explanation: Bit-pattern of 19 = 10011, Counts of continuous 1's from left to right are 1, 2 which are in increasing order. Input : 183 Output : yes Explanation: Bit-pattern
11 min read
Invert the Kth most significant bit of N
Given two non-negative integers N and K, the task is to invert the Kth most significant bit of N and print the number obtained after inverting the bit.Examples: Input: N = 10, K = 1 Output: 2 The binary representation of 10 is 1010. After inverting the first bit it becomes 0010 whose decimal equivalent is 2.Input: N = 56, K = 2 Output: 40 Approach:
7 min read
Find k-th bit in a binary string created by repeated invert and append operations
You are given an initial string s starting with "0". The string keeps duplicating as follows. Invert of it is appended to it.Examples: Input : k = 2 Output : 1 Initially s = "0". First Iteration : s = s + s' = "01" Second Iteration : s = s + s' = "0110" The digit at index 2 of s is 1. Input : k = 12 Output : 0 1. Naive Approach We can build the str
8 min read
Invert Binary Tree - Change to Mirror or Reverse
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged.  Input: 1  / \  2 3Output: 3 1 2Explanation: The tree is   1   (mirror) 1 /  \   =&gt;      /  \2    3          3   2The inorder of mirror is 3 1 2In
9 min read
Check if all bits can be made same by flipping two consecutive bits
Given a binary string, the task is to find whether all the digits of the string can be made equal i.e either 0 or 1 by flipping two consecutive bits any number of times.Examples: Input: 01011Output: YESExplanation:Flip 2nd and 3rd bit -&gt; 00111, again flipping 1'st and 2'nd bit -&gt; 11111 Input: 100011Output: NOExplanation:No number of moves can
5 min read
Flip bits of the sum of count of set bits of two given numbers
Given two numbers A and B, the task is to count the number of set bits in A and B and flip the bits of the obtained sum. Examples: Input: A = 5, B = 7Output: 2Explanation:Binary representation of A is 101.Binary representation of B is 111.Count of set bits in A and B = 2 + 3 = 5.Binary representation of the sum obtained = 101Flipping the bits of th
5 min read
Minimize cost of swapping set bits with unset bits in a given Binary string
Given a binary string S of size N, the task is to find the minimum cost by swapping every set bit with an unset bit such that the cost of swapping pairs of bits at indices i and j is abs(j - i). Note: A swapped bit can't be swapped twice and the count of set bit in the given binary string is at most N/2. Examples: Input: S = "1010001"Output: 3Expla
12 min read
Count of pairs {X, Y} from an array such that sum of count of set bits in X ⊕ Y and twice the count of set bits in X &amp; Y is M
Given an array arr[] consisting of N non-negative integers and an integer M, the task is to find the count of unordered pairs {X, Y} of array elements that satisfies the condition setBits(X ⊕ Y) + 2 * setBits(X &amp; Y) = M, where ⊕ denotes the Bitwise XOR and &amp; denotes the Bitwise AND. Examples: Input: arr[] = {30, 0, 4, 5 }, M = 2Output: 2Exp
14 min read
Print numbers having first and last bits as the only set bits
Given a positive integer n. The problem is to print numbers in the range 1 to n having first and last bits as the only set bits.Examples: Input : n = 10 Output : 1 3 5 9 (1)10 = (1)2. (3)10 = (11)2. (5)10 = (101)2. (9)10 = (1001)2 Naive Approach: Print "1". Now for i = 3 to n, check if (i-1) is a Perfect power of two or not. If true then print i. C
10 min read
Minimum number using set bits of a given number
Given an unsigned number, find the minimum number that could be formed by using the bits of the given unsigned number. Examples : Input : 6 Output : 3 Binary representation of 6 is 0000....0110. Smallest number with same number of set bits 0000....0011. Input : 11 Output : 7 Simple Approach: 1. Find binary representation of the number using simple
4 min read
Check if a number has same number of set and unset bits
Given a number N, the task is to check whether the count of the set and unset bits in the given number are same. Examples: Input: 12Output: Yes1100 is the binary representation of 12which has 2 set and 2 unset bits Input: 14Output: No Approach: Traverse in the binary representation of the given number, check if the leftmost bit is set or not using
5 min read
Maximum number of contiguous array elements with same number of set bits
Given an array with n elements. The task is to find the maximum number of contiguous array elements which have the same number of set bits. Examples: Input : arr[] = {14, 1, 2, 32, 12, 10} Output : 3 Elements 1, 2, 32 have same number of set bits and are contiguous. Input : arr[] = {1, 6, 9, 15, 8} Output : 2 Elements 6, 9 have same number of set b
6 min read
Calculate the number of set bits for every number from 0 to N
Given a non-negative integer N, the task is to find the count of set bits for every number from 0 to N.Examples: Input: N = 3 Output: 0 1 1 2 0, 1, 2 and 3 can be written in binary as 0, 1, 10 and 11. The number of 1's in their binary representation are 0, 1, 1 and 2.Input: N = 5 Output: 0 1 1 2 1 2 Naive approach: Run a loop from 0 to N and using
9 min read
Find the largest number smaller than integer N with maximum number of set bits
Given an integer N, the task is to find the largest number smaller than N having the maximum number of set bits.Examples: Input : N = 345 Output : 255 Explanation: 345 in binary representation is 101011001 with 5 set bits, and 255 is 11111111 with maximum number of set bits less than the integer N.Input : N = 2 Output : 1 Explanation: 2 in binary r
8 min read
Next higher number with same number of set bits
Given a number x, find next number with same number of 1 bits in it's binary representation.For example, consider x = 12, whose binary representation is 1100 (excluding leading zeros on 32 bit machine). It contains two logic 1 bits. The next higher number with two logic 1 bits is 17 (100012).Algorithm:When we observe the binary sequence from 0 to 2
8 min read
M-th smallest number having k number of set bits.
Given two non-negative integers m and k. The problem is to find the m-th smallest number having k number of set bits.Constraints: 1 &lt;= m, k.Examples: Input : m = 4, k = 2 Output : 9 (9)10 = (1001)2, it is the 4th smallest number having 2 set bits. Input : m = 6, k = 4 Output : 39 Approach: Following are the steps: Find the smallest number having
6 min read
Number of integers with odd number of set bits
Given a number n, count number of integers smaller than or equal to n that have odd number of set bits.Examples: Input : 5 Output : 3 Explanation : Integers with odd number of set bits in range 1 to 5 : 0 contains 0 set bits 1 contains 1 set bits 2 contains 1 set bits 3 contains 2 set bits 4 contains 1 set bits 5 contains 2 set bits Input : 10 Outp
6 min read
Toggle all the bits of a number except k-th bit.
Given a positive (or unsigned) integer n, write a function to toggle all the bits except k-th bit. Here value of k starts from 0 (zero) and from right. Examples: Input : n = 4294967295, k = 0 Output : 1 The number 4294967295 in 32 bits has all bits set. When we toggle all bits except last bit, we get 1. Input : n = 1, k = 1 Output : 4294967292 4294
4 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 problem quickly in Python. Approach is very simple,
4 min read
Smallest number whose set bits are maximum in a given range
Given a positive integer 'l' and 'r'. Find the smallest number 'n' such that l &lt;= n &lt;= r and count of the number of set bits(number of '1's in binary representation) is as maximum as possible. Examples : Input: 1 4Output: 3Explanation:Binary representation from '1' to '4':110 = 0012210 = 0102310 = 0112110 = 1002Thus number '3' has maximum set
9 min read
Increment a number by one by manipulating the bits
Given a non-negative integer n. The problem is to increment n by 1 by manipulating the bits of n.Examples : Input : 6 Output : 7 Input : 15 Output : 16 Approach: Following are the steps: Get the position of rightmost unset bit of n. Let this position be k.Set the k-th bit of n.Toggle the last k-1 bits of n.Finally, return n. C/C++ Code // C++ imple
7 min read
Toggle first and last bits of a number
Given a number n, the task is to toggle only first and last bits of a numberExamples : Input : 10 Output : 3 Binary representation of 10 is 1010. After toggling first and last bits, we get 0011. Input : 15 Output : 6 Prerequisite : Find MSB of given number.1) Generate a number which contains first and last bit as set. We need to change all middle b
8 min read
Toggle all even bits of a number
Given a number, the task is to Toggle all even bit of a numberExamples: Input : 10 Output : 0 binary representation 1 0 1 0 after toggle 0 0 0 0 Input : 20 Output : 30 binary representation 1 0 1 0 0 after toggle 1 1 1 1 0 1. First generate a number that contains even position bits. 2. Take XOR with the original number. Note that 1 ^ 1 = 0 and 1 ^
8 min read
Toggle all odd bits of a number
Given n number, the task is to toggle odd bit of the number.Examples: Input : 10 Output : 15 binary representation 1 0 1 0 after toggle 1 1 1 1 Input : 20 Output : 1 binary representation 1 0 1 0 0 after toggle 0 0 0 0 1 1. First generate a number that contains odd position bits. 2. Take XOR with the original number. Note that 1 ^ 1 = 0 and 1 ^ 0 =
4 min read
For every set bit of a number toggle bits of other
Given two integer numbers, whenever the bits of the first number is set i.e. 1, toggle the bits of the second number leaving the rest bits of the second number unchanged. Examples : Input: 2 5 Output: 7 2 is represented as 10 in binary and 5 is represented as 101. Hence toggling the 2nd bit of 5 from right, thus the new number becomes 7 i.e. 111 In
3 min read
Article Tags :
Practice Tags :