The Wayback Machine - https://web.archive.org/web/20241104020734/https://www.geeksforgeeks.org/swap-bits-in-a-given-number/
Open In App

Swap bits in a given number

Last Updated : 02 Sep, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Easy
69.49%
6.7K

Given a number x and two positions (from the right side) in the binary representation of x, write a function that swaps n bits at the given two positions and returns the result. It is also given that the two sets of bits do not overlap.

Recommended Practice

Method 1 
Let p1 and p2 be the two given positions.

Example 1 

Input:
x = 47 (00101111)
p1 = 1 (Start from the second bit from the right side)
p2 = 5 (Start from the 6th bit from the right side)
n = 3 (No of bits to be swapped)
Output:
227 (11100011)
The 3 bits starting from the second bit (from the right side) are 
swapped with 3 bits starting from 6th position (from the right side)

Example 2 

Input:
x = 28 (11100)
p1 = 0 (Start from first bit from right side)
p2 = 3 (Start from 4th bit from right side)
n = 2 (No of bits to be swapped)
Output:
7 (00111)
The 2 bits starting from 0th position (from right side) are
swapped with 2 bits starting from 4th position (from right side)

Solution 
We need to swap two sets of bits. XOR can be used in a similar way as it is used to swap 2 numbers. Following is the algorithm. 

1) Move all bits of the first set to the rightmost side
   set1 =  (x >> p1) & ((1U << n) - 1)
Here the expression (1U << n) - 1 gives a number that 
contains last n bits set and other bits as 0. We do & 
with this expression so that bits other than the last 
n bits become 0.
2) Move all bits of second set to rightmost side
   set2 =  (x >> p2) & ((1U << n) - 1)
3) XOR the two sets of bits
   xor = (set1 ^ set2) 
4) Put the xor bits back to their original positions. 
   xor = (xor << p1) | (xor << p2)
5) Finally, XOR the xor with original number so 
   that the two sets are swapped.
   result = x ^ xor

Implementation: 

C++




// C++ Program to swap bits
// in a given number
#include <bits/stdc++.h>
using namespace std;
 
int swapBits(unsigned int x, unsigned int p1,
             unsigned int p2, unsigned int n)
{
    /* Move all bits of first set to rightmost side */
    unsigned int set1 = (x >> p1) & ((1U << n) - 1);
 
    /* Move all bits of second set to rightmost side */
    unsigned int set2 = (x >> p2) & ((1U << n) - 1);
 
    /* Xor the two sets */
    unsigned int Xor = (set1 ^ set2);
 
    /* Put the Xor bits back to their original positions */
    Xor = (Xor << p1) | (Xor << p2);
 
    /* Xor the 'Xor' with the original number so that the
    two sets are swapped */
    unsigned int result = x ^ Xor;
 
    return result;
}
 
/* Driver code*/
int main()
{
    int res = swapBits(28, 0, 3, 2);
    cout << "Result = " << res;
    return 0;
}
 
// This code is contributed by rathbhupendra


C




// C Program to swap bits
// in a given number
#include <stdio.h>
 
int swapBits(unsigned int x, unsigned int p1, unsigned int p2, unsigned int n)
{
    /* Move all bits of first set to rightmost side */
    unsigned int set1 = (x >> p1) & ((1U << n) - 1);
 
    /* Move all bits of second set to rightmost side */
    unsigned int set2 = (x >> p2) & ((1U << n) - 1);
 
    /* XOR the two sets */
    unsigned int xor = (set1 ^ set2);
 
    /* Put the xor bits back to their original positions */
    xor = (xor << p1) | (xor << p2);
 
    /* XOR the 'xor' with the original number so that the
       two sets are swapped */
    unsigned int result = x ^ xor;
 
    return result;
}
 
/* Driver program to test above function*/
int main()
{
    int res = swapBits(28, 0, 3, 2);
    printf("\nResult = %d ", res);
    return 0;
}


Java




// Java Program to swap bits
// in a given number
 
class GFG {
 
    static int swapBits(int x, int p1, int p2, int n)
    {
        // Move all bits of first set
        // to rightmost side
        int set1 = (x >> p1) & ((1 << n) - 1);
 
        // Move all bits of second set
        // to rightmost side
        int set2 = (x >> p2) & ((1 << n) - 1);
 
        // XOR the two sets
        int xor = (set1 ^ set2);
 
        // Put the xor bits back to
        // their original positions
        xor = (xor << p1) | (xor << p2);
 
        // XOR the 'xor' with the original number
        // so that the  two sets are swapped
        int result = x ^ xor;
 
        return result;
    }
 
    // Driver program
    public static void main(String[] args)
    {
        int res = swapBits(28, 0, 3, 2);
        System.out.println("Result = " + res);
    }
}
 
// This code is contributed by prerna saini.


Python3




# Python program to
# swap bits in a given number
 
def swapBits(x, p1, p2, n):
 
    # Move all bits of first
    # set to rightmost side
    set1 =  (x >> p1) & ((1<< n) - 1)
  
    # Move all bits of second
    # set to rightmost side
    set2 =  (x >> p2) & ((1 << n) - 1)
  
    # XOR the two sets
    xor = (set1 ^ set2)
  
    # Put the xor bits back
    # to their original positions
    xor = (xor << p1) | (xor << p2)
  
      # XOR the 'xor' with the
      # original number so that the
      # two sets are swapped
    result = x ^ xor
  
    return result
     
# Driver code
 
res = swapBits(28, 0, 3, 2)
print("Result =", res)
 
# This code is contributed
# by Anant Agarwal.


C#




// C# Program to swap bits
// in a given number
using System;
 
class GFG {
 
    static int swapBits(int x, int p1, int p2, int n)
    {
        // Move all bits of first
        // set to rightmost side
        int set1 = (x >> p1) & ((1 << n) - 1);
 
        // Move all bits of second set
        // set to rightmost side
        int set2 = (x >> p2) & ((1 << n) - 1);
 
        // XOR the two sets
        int xor = (set1 ^ set2);
 
        // Put the xor bits back to
        // their original positions
        xor = (xor << p1) | (xor << p2);
 
        // XOR the 'xor' with the original number
        // so that the two sets are swapped
        int result = x ^ xor;
 
        return result;
    }
 
    // Driver program
    public static void Main()
    {
        int res = swapBits(28, 0, 3, 2);
        Console.WriteLine("Result = " + res);
    }
}
 
// This code is contributed by vt_m.


PHP




<?php
// PHP Program to swap bits
// in a given number
 
// function returns
// the swapped bits
function swapBits($x, $p1, $p2, $n)
{
     
    // Move all bits of first
    // set to rightmost side
    $set1 = ($x >> $p1) &
            ((1 << $n) - 1);
 
    // Move all bits of second
    // set to rightmost side
    $set2 = ($x >> $p2) &
            ((1 << $n) - 1);
 
    // XOR the two sets
    $xor = ($set1 ^ $set2);
 
    // Put the xor bits back to
    // their original positions
    $xor = ($xor << $p1) |
           ($xor << $p2);
 
    // XOR the 'xor' with the
    // original number so that
    // the two sets are swapped
    $result = $x ^ $xor;
 
    return $result;
}
 
    // Driver Code
    $res = swapBits(28, 0, 3, 2);
    echo "\nResult = ", $res;
     
// This code is contributed by anuj_67.
?>


Javascript




<script>
 
// Javascript Program to swap bits
// in a given number
 
 
    function  swapBits(x, p1, p2, n)
    {
        // Move all bits of first set
        // to rightmost side
        let set1 = (x >> p1) & ((1 << n) - 1);
 
        // Move all bits of second set
        // to rightmost side
        let set2 = (x >> p2) & ((1 << n) - 1);
 
        // XOR the two sets
        let xor = (set1 ^ set2);
 
        // Put the xor bits back to
        // their original positions
        xor = (xor << p1) | (xor << p2);
 
        // XOR the 'xor' with the original number
        // so that the  two sets are swapped
        let result = x ^ xor;
 
        return result;
    }
 
// Driver Code
 
    let res = swapBits(28, 0, 3, 2);
    document.write("Result = " + res);
 
</script>


Output

Result = 7

Time Complexity: O(1), as we are using constant-time operations.

Auxiliary Space: O(1), as we are not using any extra space.

Following is a shorter implementation of the same logic 

C++




// C++ program of the above approach
#include <bits/stdc++.h>
using namespace std;
 
int swapBits(int x, int p1, int p2, int n)
{
    /* xor contains xor of two sets */
    int xor = ((x >> p1) ^ (x >> p2)) & ((1U << n) - 1);
 
    /* To swap two sets, we need to again XOR the xor with
     * original sets */
    return x ^ ((xor << p1) | (xor << p2));
}
 
// This code is contributed by splevel62.


C




int swapBits(unsigned int x, unsigned int p1, unsigned int p2, unsigned int n)
{
    /* xor contains xor of two sets */
    unsigned int xor = ((x >> p1) ^ (x >> p2)) & ((1U << n) - 1);
 
    /* To swap two sets, we need to again XOR the xor with original sets */
    return x ^ ( (xor << p1) | (xor << p2));
}


Java




static int swapBits(int x, int p1, int p2, int n)
{
    /* xor contains xor of two sets */
    int xor = ((x >> p1) ^ (x >> p2)) & ((1U << n) - 1);
 
    /* To swap two sets, we need to again XOR the xor with
     * original sets */
    return x ^ ((xor << p1) | (xor << p2));
}
 
// This code is contributed by subhammahato348.


Python3




# Python code to implement the approach
def swapBits(x, p1, p2, n) :
     
    # xor contains xor of two sets
    xor = (((x >> p1) ^ (x >> p2)) & ((1 << n) - 1))
  
    # To swap two sets, we need to again XOR the xor with original sets
    return x ^ ( (xor << p1) | (xor << p2))
   
  # This code is contributed by sanjoy_62.


C#




static int swapBits(int x, int p1, int p2, int n)
{
    /* xor contains xor of two sets */
    int xor = ((x >> p1) ^ (x >> p2)) & ((1U << n) - 1);
 
    /* To swap two sets, we need to again XOR the xor with
     * original sets */
    return x ^ ((xor << p1) | (xor << p2));
}
 
// This code is contributed by subhammahato348.


Javascript




<script>
    // JavaScript code for the above approach
function swapBits(x, p1, p2, n)
{
    /* xor contains xor of two sets */
    let xor = ((x >> p1) ^ (x >> p2)) & ((1 << n) - 1);
 
    /* To swap two sets, we need to again XOR the xor with
     * original sets */
    return x ^ ((xor << p1) | (xor << p2));
}
 
// This code is contributed by avijitmondal1998.
</script>


Time Complexity: O(1), as we are using constant-time operations.

Auxiliary Space: O(1), as we are not using any extra space.

Method 2 – 
This solution focuses on calculating the values of bits to be swapped using AND gate. Then we can set/unset those bits based on whether the bits are to be swapped. For the number of bits to be swapped (n) – 

  • Calculate shift1 = The value after setting bit at p1 position to 1
  • Calculate shift2 = The value after setting bit at p2 position to 1
  • value1 = Number to check if num at position p1 is set or not.
  • value2 = Number to check if num at position p2 is set or not.
  • If value1 and value2 are different is when we have to swap the bits.

Example: 

[28 0 3 2] num=28 (11100) p1=0 p2=3 n=2
   Given = 11100
   Required output = 00111 i.e. (00)1(11) msb 2 bits replaced with lsb 2 bits

n=2
  p1=0,  p2=3
  shift1= 1,  shift2= 1000
  value1= 0,  value2= 1000
 After swap
  num= 10101

n=3
  p1=1,  p2=4
  shift1= 10,  shift2= 10000
  value1= 0,  value2= 10000
 After swap
  num= 00111

Implementation 

C++




#include <iostream>
using namespace std;
 
int swapBits(unsigned int num, unsigned int p1,
             unsigned int p2, unsigned int n)
{
    int shift1, shift2, value1, value2;
    while (n--) {
        // Setting bit at p1 position to 1
        shift1 = 1 << p1;
        // Setting bit at p2 position to 1
        shift2 = 1 << p2;
 
        // value1 and value2 will have 0 if num
        // at the respective positions - p1 and p2 is 0.
        value1 = ((num & shift1));
        value2 = ((num & shift2));
 
        // check if value1 and value2 are different
        // i.e. at one position bit is set and other it is not
        if ((!value1 && value2) || (!value2 && value1)) {
            // if bit at p1 position is set
            if (value1) {
                // unset bit at p1 position
                num = num & (~shift1);
                // set bit at p2 position
                num = num | shift2;
            }
            // if bit at p2 position is set
            else {
                // set bit at p2 position
                num = num & (~shift2);
                // unset bit at p2 position
                num = num | shift1;
            }
        }
        p1++;
        p2++;
    }
    // return final result
    return num;
}
 
/* Driver code*/
int main()
{
    int res = swapBits(28, 0, 3, 2);
    cout << "Result = " << res;
    return 0;
}


Java




class GFG
{
    static int swapBits(int num, int p1, int p2, int n)
    {
        int shift1, shift2, value1, value2;
        while (n-- > 0)
        {
           
            // Setting bit at p1 position to 1
            shift1 = 1 << p1;
           
            // Setting bit at p2 position to 1
            shift2 = 1 << p2;
       
            // value1 and value2 will have 0 if num
            // at the respective positions - p1 and p2 is 0.
            value1 = ((num & shift1));
            value2 = ((num & shift2));
       
            // check if value1 and value2 are different
            // i.e. at one position bit is set and other it is not
            if ((value1 == 0 && value2 != 0) ||
                (value2 == 0 && value1 != 0))
            {
               
                // if bit at p1 position is set
                if (value1 != 0)
                {
                   
                    // unset bit at p1 position
                    num = num & (~shift1);
                   
                    // set bit at p2 position
                    num = num | shift2;
                }
               
                // if bit at p2 position is set
                else
                {
                   
                    // set bit at p2 position
                    num = num & (~shift2);
                   
                    // unset bit at p2 position
                    num = num | shift1;
                }
            }
            p1++;
            p2++;
        }
       
        // return final result
        return num;
    }
   
  // Driver code
  public static void main(String[] args)
  {
    int res = swapBits(28, 0, 3, 2);
    System.out.println("Result = " + res);
  }
}
 
// This code is contributed by divyeshrabadiya07


Python3




def swapBits(num, p1, p2, n):
    shift1 = 0
    shift2 = 0
    value1 = 0
    value2 = 0
 
    while(n > 0):
       
        # Setting bit at p1 position to 1
        shift1 = 1 << p1
 
        # Setting bit at p2 position to 1
        shift2 = 1 << p2
 
        # value1 and value2 will have 0 if num
        # at the respective positions - p1 and p2 is 0.
        value1 = ((num & shift1))
        value2 = ((num & shift2))
 
        # check if value1 and value2 are different
        # i.e. at one position bit is set and other it is not
        if((value1 == 0 and value2 != 0) or (value2 == 0 and value1 != 0)):
             
            # if bit at p1 position is set
            if(value1 != 0):
 
                # unset bit at p1 position
                num = num & (~shift1)
 
                # set bit at p2 position
                num = num | shift2
 
            # if bit at p2 position is set
            else:
 
                # set bit at p2 position
                num = num & (~shift2)
 
                # unset bit at p2 position
                num = num | shift1
        p1 += 1
        p2 += 1
        n -= 1
 
    # return final result
    return num
 
# Driver code
res = swapBits(28, 0, 3, 2)
print("Result =", res)
 
# This code is contributed by avanitrachhadiya2155


C#




using System;
class GFG
{
     
  static int swapBits(int num, int p1,
                      int p2, int n)
  {
    int shift1, shift2, value1, value2;
    while (n-- > 0)
    {
 
      // Setting bit at p1 position to 1
      shift1 = 1 << p1;
 
      // Setting bit at p2 position to 1
      shift2 = 1 << p2;
 
      // value1 and value2 will have 0 if num
      // at the respective positions - p1 and p2 is 0.
      value1 = ((num & shift1));
      value2 = ((num & shift2));
 
      // check if value1 and value2 are different
      // i.e. at one position bit is set and other it is not
      if ((value1 == 0 && value2 != 0) || (value2 == 0 && value1 != 0))
      {
 
        // if bit at p1 position is set
        if (value1 != 0)
        {
 
          // unset bit at p1 position
          num = num & (~shift1);
 
          // set bit at p2 position
          num = num | shift2;
        }
 
        // if bit at p2 position is set
        else
        {
 
          // set bit at p2 position
          num = num & (~shift2);
 
          // unset bit at p2 position
          num = num | shift1;
        }
      }
      p1++;
      p2++;
    }
 
    // return final result
    return num;
  }
 
  // Driver code
  static void Main()
  {
    int res = swapBits(28, 0, 3, 2);
    Console.WriteLine("Result = " + res);
  }
}
 
// This code is contributed by divyesh072019


Javascript




<script>
 
function swapBits(num, p1, p2, n)
{
    let shift1, shift2, value1, value2;
     
    while (n-- > 0)
    {
     
        // Setting bit at p1 position to 1
        shift1 = 1 << p1;
         
        // Setting bit at p2 position to 1
        shift2 = 1 << p2;
         
        // value1 and value2 will have 0 if num
        // at the respective positions - p1 and p2 is 0.
        value1 = ((num & shift1));
        value2 = ((num & shift2));
         
        // Check if value1 and value2 are different
        // i.e. at one position bit is set and
        // other it is not
        if ((value1 == 0 && value2 != 0) ||
            (value2 == 0 && value1 != 0))
        {
         
            // If bit at p1 position is set
            if (value1 != 0)
            {
             
                // Unset bit at p1 position
                num = num & (~shift1);
                 
                // Set bit at p2 position
                num = num | shift2;
            }
                 
            // If bit at p2 position is set
            else
            {
             
                // Set bit at p2 position
                num = num & (~shift2);
                 
                // Unset bit at p2 position
                num = num | shift1;
            }
        }
        p1++;
        p2++;
    }
     
    // Return final result
    return num;
}
 
// Driver code
let res = swapBits(28, 0, 3, 2);
 
document.write("Result = " + res);
 
// This code is contributed by suresh07
     
</script>


Output

Result = 7

Time Complexity: O(N), as we are using a loop to traverse N times. Where N is the number of bits to be swapped.

Auxiliary Space: O(1), as we are not using any extra space.
References: 
Swapping individual bits with XOR 

 



Previous Article
Next Article

Similar Reads

How to swap two bits in a given integer?
Given an integer n and two-bit positions p1 and p2 inside it, swap bits at the given positions. The given positions are from the least significant bit (lsb). For example, the position for lsb is 0.Examples: Input: n = 28, p1 = 0, p2 = 3Output: 21Explanation: 28 in binary is 11100. If we swap 0'th and 3rd digits, we get 10101 which is 21 in decimal.
8 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
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 > 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
Swap all odd and even bits
Given an unsigned integer N. The task is to swap all odd bits with adjacent even bits. Examples: Input: 23Output: 43Explanation: 23 (00010111) should be converted to 43 (00101011). Input: 2Output: 1 Recommended PracticeSwap all odd and even bitsTry It! Naive Approach: Below is the idea to solve the problem For every even index i in the binary repre
10 min read
Swap every two bits in bytes
Swap all the pair of bits in a byte. Before swapping: 11-10-11-01 After swapping: 11-01-11-10Examples: Input : 00000010 Output : 00000001 Input : 00000100 Output : 00001000 Approach: x = ((x & 0x55555555) >> 1) | ((x & 0xAAAAAAAA) <> 1 extracts the high bit position and shifts it to the low bit position. Similarly the expression
3 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 -> 00111, again flipping 1'st and 2'nd bit -> 11111 Input: 100011Output: NOExplanation:No number of moves can
5 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 & 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 & Y) = M, where ⊕ denotes the Bitwise XOR and & 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
Largest even number possible by using one swap operation in given number
Given an odd number in the form of a string, the task is to make the largest even number from the given number, and you are allowed to do only one swap operation. Examples : Input: 1235785Output: 1535782Explanation: Swap 2 and 5. Input: 536425Output: 536524Explanation: Swap 4 and 5 to make the largest even number. Recommended PracticeOdd to EvenTry
6 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
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 <= n <= 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
Count number of bits changed after adding 1 to given N
Given an integer [Tex]N [/Tex]. The task is to find the number of bits changed after adding 1 to the given number.Examples: Input : N = 5 Output : 2 After adding 1 to 5 it becomes 6. Binary representation of 5 is 101. Binary representation of 6 is 110. So, no. of bits changed is 2. Input : N = 1 Output : 2 There are three approaches to find the num
4 min read
Unset least significant K bits of a given number
Given an integer N, the task is to print the number obtained by unsetting the least significant K bits from N. Examples: Input: N = 200, K=5Output: 192Explanation: (200)10 = (11001000)2 Unsetting least significant K(= 5) bits from the above binary representation, the new number obtained is (11000000)2 = (192)10 Input: N = 730, K = 3Output: 720 Appr
4 min read
Flip consecutive set bits starting from LSB of a given number
Given a positive integer N, the task is to find the number that can be obtained by flipping consecutive set bits starting from the LSB in the binary representation of N. Examples: Input: N = 39Output: 32Explanation:Binary representation of (39)10 = (100111)2After flipping all consecutive set bits starting from the LSB, the number obtained is (10000
6 min read
Flip all K-bits of a given number
Given two integers N and K, the task is to represent N in K bits and print the number obtained after flipping all the bits. Examples: Input:N = 1, K = 32Output: 4294967294Explanation:1 in K(= 32) bit representation is (00000000000000000000000000000001)2.Flipping all the bits modifies N to (11111111111111111111111111111110)2 = (4294967294)10. Input:
3 min read
Minimum number of flipping adjacent bits required to make given Binary Strings equal
Given two binary strings s1[] and s2[] of the same length N, the task is to find the minimum number of operations to make them equal. Print -1 if it is impossible to do so. One operation is defined as choosing two adjacent indices of one of the binary string and inverting the characters at those positions, i.e, 1 to 0 and vice-versa. Examples: Inpu
7 min read
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
Maximize a given unsigned number by swapping bits at it's extreme positions.
Given a number maximize it by swapping bits at its extreme positions i.e. at the first and last position, second and second last position, and so on. Examples: Input : 4 (0000...0100) Output : 536870912 (0010...0000) In the above example swapped 3rd and 3rd last bit to maximize the given unsigned number. Input : 12 (00000...1100) Output : 805306368
5 min read
Extract 'k' bits from a given position in a number.
How to extract 'k' bits from a given position 'p' in a number? Examples: Input : number = 171 k = 5 p = 2 Output : The extracted number is 21 171 is represented as 10101011 in binary, so, you should get only 10101 i.e. 21. Input : number = 72 k = 5 p = 1 Output : The extracted number is 8 72 is represented as 1001000 in binary, so, you should get o
4 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.Examples : Input : n = 17, l = 2, r = 3 Output : 23
5 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 <= 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
Pairwise Swap Nodes of a given linked list by changing links
Given a singly linked list, write a function to swap elements pairwise. For example, if the linked list is 1->2->3->4->5->6->7 then the function should change it to 2->1->4->3->6->5->7, and if the linked list is 1->2->3->4->5->6 then the function should change it to 2->1->4->3->6->5
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg