The Wayback Machine - https://web.archive.org/web/20241001173300/https://www.geeksforgeeks.org/reverse-actual-bits-given-number/
Open In App

Reverse actual bits of the given number

Last Updated : 12 Apr, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Solve Problem
Easy
75.04%
5K

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 : 11
Output : 13
Explanation: (11)10 = (1011)2.
After reversing the bits we get:
(1101)2 = (13)10.

Input : 10
Output : 5
Explanation : (10)10 = (1010)2.
After reversing the bits we get:
(0101)2 = (101)2
        = (5)10.

Recommended Practice

In this approach, one by one bit in the binary representation of n is being obtained with the help of bitwise right shift operation and they are being accumulated in rev with the help of bitwise left shift operation. 
Algorithm: 
 

 

C++




// C++ implementation to reverse bits of a number
#include <bits/stdc++.h>
 
using namespace std;
 
// function to reverse bits of a number
unsigned int reverseBits(unsigned int n)
{
    unsigned int rev = 0;
 
    // traversing bits of 'n' from the right
    while (n > 0) {
        // bitwise left shift
        // 'rev' by 1
        rev <<= 1;
 
        // if current bit is '1'
        if (n & 1 == 1)
            rev ^= 1;
 
        // bitwise right shift
        // 'n' by 1
        n >>= 1;
    }
 
    // required number
    return rev;
}
 
// Driver program to test above
int main()
{
    unsigned int n = 11;
    cout << reverseBits(n);
    return 0;
}


C




// C implementation to reverse bits of a number
#include <stdio.h>
 
// function to reverse bits of a number
unsigned int reverseBits(unsigned int n)
{
    unsigned int rev = 0;
 
    // traversing bits of 'n' from the right
    while (n > 0) {
        // bitwise left shift 'rev' by 1
        rev <<= 1;
 
        // if current bit is '1'
        if (n & 1 == 1)
            rev ^= 1;
 
        // bitwise right shift 'n' by 1
        n >>= 1;
    }
    // required number
    return rev;
}
 
// Driver program to test above
int main()
{
    unsigned int n = 11;
    printf("%u", reverseBits(n));
    return 0;
}
 
// This code is contributed by Sania Kumari Gupta
// (kriSania804)


Java




import java.io.*;
 
// Java implementation to
// reverse bits of a number
class GFG {
    // function to reverse bits of a number
    public static int reverseBits(int n)
    {
        int rev = 0;
 
        // traversing bits of 'n'
        // from the right
        while (n > 0) {
            // bitwise left shift
            // 'rev' by 1
            rev <<= 1;
 
            // if current bit is '1'
            if ((int)(n & 1) == 1)
                rev ^= 1;
 
            // bitwise right shift
            //'n' by 1
            n >>= 1;
        }
        // required number
        return rev;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int n = 11;
        System.out.println(reverseBits(n));
    }
}
 
// This code is contributed
// by prerna saini.


Python3




# Python 3 implementation to
# reverse bits of a number
 
 
# function to reverse
# bits of a number
def reverseBits(n):
 
    rev = 0
 
    # traversing bits of 'n' from the right
    while (n > 0):
 
        # bitwise left shift 'rev' by 1
        rev = rev << 1
 
        # if current bit is '1'
        if (n & 1 == 1):
            rev = rev ^ 1
 
        # bitwise right shift 'n' by 1
        n = n >> 1
 
    # required number
    return rev
 
 
# Driver code
n = 11
print(reverseBits(n))
 
 
# This code is contributed
# by Nikita Tiwari.


C#




// C# implementation to
// reverse bits of a number
using System;
class GFG {
    // function to reverse bits of a number
    public static int reverseBits(int n)
    {
        int rev = 0;
 
        // traversing bits of 'n'
        // from the right
        while (n > 0) {
            // bitwise left shift
            // 'rev' by 1
            rev <<= 1;
 
            // if current bit is '1'
            if ((int)(n & 1) == 1)
                rev ^= 1;
 
            // bitwise right shift
            //'n' by 1
            n >>= 1;
        }
        // required number
        return rev;
    }
 
    // Driver code
    public static void Main()
    {
        int n = 11;
        Console.WriteLine(reverseBits(n));
    }
}
 
// This code is contributed
// by vt_m.


PHP




<?php
// PHP implementation to reverse
// bits of a number
 
// function to reverse
// bits of a number
function reverseBits($n)
{
    $rev = 0;
     
    // traversing bits of 'n'
    // from the right
    while ($n > 0)
    {
        // bitwise left shift
        // 'rev' by 1
        $rev <<= 1;
         
        // if current bit is '1'
        if ($n & 1 == 1)
            $rev ^= 1;
         
        // bitwise right shift
        // 'n' by 1
        $n >>= 1;
             
    }
     
    // required number
    return $rev;
}
 
// Driver code
$n = 11;
echo reverseBits($n);
 
// This code is contributed by mits
?>


Javascript




<script>
 
// JavaScript program  to
// reverse bits of a number
 
    // function to reverse bits of a number
    function reverseBits(n)
    {
        let rev = 0;
   
        // traversing bits of 'n'
        // from the right
        while (n > 0)
        {
            // bitwise left shift
            // 'rev' by 1
            rev <<= 1;
   
            // if current bit is '1'
            if ((n & 1) == 1)
                rev ^= 1;
   
            // bitwise right shift
            //'n' by 1
            n >>= 1;
        }
        // required number
        return rev;
    }
 
// Driver code
 
        let n = 11;
        document.write(reverseBits(n));
 
</script>


Output

13

Time Complexity: O(num), where num is the number of bits in the binary representation of n.
Space Complexity: O(1)
 

How about considering even the leading zero bits for the reversal?

Another twist to this problem is to reverse all 4 bytes of an integer value. For e.g. if the number is 11 (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1) then its reverse will be -805306368 (1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0).

C++




#include <iostream>
#include <vector>
 
using namespace std;
 
// helper method to show actual bits
void showBits(int n) {
    vector<int> bits;
    for(int i = 0; i < sizeof(int) * 8; i++) {
        if((n & 1) > 0) bits.push_back(1);
        else bits.push_back(0);
        n = n >> 1;
    }
    for(int i = bits.size()-1; i >= 0; i--) {
        cout << bits[i] << ",";
    }
}
 
int reverseBits(int n) {
    int newN = 0;
    for(int i = 0; i < sizeof(int) * 8; i++) {
        newN = newN << 1;
        if((n & 1) > 0) {
            newN = newN ^ 1;
        }
        n = n >> 1;
    }
    return newN;
}
 
int main() {
    int num = 11;
    // just to show full bit sequence
    showBits(num);
    int ret = reverseBits(num);
    cout << "\nreverse of number " << num << " is=" << ret << endl;
    showBits(ret);
 
    cout << "\n";
 
    num = -10;
    // just to show full bit sequence
    showBits(num);
    ret = reverseBits(num);
    cout << "\nreverse of number " << num << " is=" << ret << endl;
    showBits(ret);
 
    return 0;
}
 
 
// This code is contributed by Shivhack999


Java




/*package whatever //do not write package name here */
 
import java.io.*;
import java.util.List;
import java.util.ArrayList;
 
class ReverseBits190 {
    public static void main (String[] args) {
          int num = 11;
        showBits(num); // just to show full bit sequence
          int ret = reverseBits(num);
        System.out.println("\nreverse of number " + num + " is=" + ret);
          showBits(ret);
 
          System.out.println("\n");
        num = -10;
        showBits(num); // just to show full bit sequence
          ret = reverseBits(num);
        System.out.println("\nreverse of number " + num + " is=" + ret);
          showBits(ret);
    }
 
      static int reverseBits(int n) {
        int newN = 0;
        for(int i = 0; i < Integer.SIZE; i++) {
            newN = newN << 1;
            if((n & 1) > 0) {
                newN = newN ^ 1;
            }
            n = n >> 1;
        }
        return newN;
    }
 
  // helper method to show actual bits
      static void showBits(int n) {
        List<Integer> l = new ArrayList<>();
        for(int i = 0; i< Integer.SIZE; i++) {
             
            if((n & 1) > 0) l.add(1);
            else l.add(0);
             
            n = n >> 1;
        }
        for(int i = l.size()-1; i >= 0; i--) {
            System.out.print(l.get(i) + ",");
        }
    }
}


C#




using System;
using System.Collections.Generic;
 
public class MainClass {
    public static void Main() {
        int num = 11;
        // just to show full bit sequence
        ShowBits(num);
        int ret = ReverseBits(num);
        Console.WriteLine("\nreverse of number " + num + " is=" + ret);
        ShowBits(ret);
 
        Console.WriteLine("\n");
 
        num = -10;
        // just to show full bit sequence
        ShowBits(num);
        ret = ReverseBits(num);
        Console.WriteLine("\nreverse of number " + num + " is=" + ret);
        ShowBits(ret);
    }
 
    // helper method to show actual bits
    public static void ShowBits(int n) {
        List<int> bits = new List<int>();
        for(int i = 0; i < sizeof(int) * 8; i++) {
            if((n & 1) > 0) bits.Add(1);
            else bits.Add(0);
            n = n >> 1;
        }
        for(int i = bits.Count-1; i >= 0; i--) {
            Console.Write(bits[i] + ",");
        }
    }
 
    public static int ReverseBits(int n) {
        int newN = 0;
        for(int i = 0; i < sizeof(int) * 8; i++) {
            newN = newN << 1;
            if((n & 1) > 0) {
                newN = newN ^ 1;
            }
            n = n >> 1;
        }
        return newN;
    }
}
 
// This code is contributed by shivregkec


Python3




def show_bits(n):
    bits = []
    for i in range(32):
        if n & 1:
            bits.append(1)
        else:
            bits.append(0)
        n >>= 1
    bits.reverse()
    print(bits)
 
def reverse_bits(n):
    new_n = 0
    for i in range(32):
        new_n <<= 1
        if n & 1:
            new_n ^= 1
        n >>= 1
    return new_n
 
num = 11
# just to show full bit sequence
show_bits(num)
ret = reverse_bits(num)
print("reverse of number", num, "is=", ret)
show_bits(ret)
 
print()
 
num = -10
# just to show full bit sequence
show_bits(num)
ret = reverse_bits(num)
print("reverse of number", num, "is=", ret)
show_bits(ret)


Javascript




// helper function to show actual bits
function showBits(n) {
let bits = [];
for (let i = 0; i < 32; i++) {
if (n & 1) {
bits.push(1);
} else {
bits.push(0);
}
n >>= 1;
}
bits.reverse();
console.log(bits);
}
 
function reverseBits(n) {
let newN = 0;
for (let i = 0; i < 32; i++) {
newN <<= 1;
if (n & 1) {
newN ^= 1;
}
n >>= 1;
}
return newN;
}
 
let num = 11;
// just to show full bit sequence
showBits(num);
let ret = reverseBits(num);
console.log('reverse of number ${num} is= ${ret}');
showBits(ret);
 
console.log();
 
num = -10;
// just to show full bit sequence
showBits(num);
ret = reverseBits(num);
console.log('reverse of number ${num} is= ${ret}');
showBits(ret);


Output

0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,
reverse of number 11 is=-805306368
1,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,

1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,0,
reverse of number -10 is=1879048191
0,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,

Contributed by Nikhil.

*************************************************************************************************************************

Another way using c++

Note: All 32bits are reversed, All leading 0’s are being considered using c++.

Examples :

Input : 4
Output : 536870912
Explanation:  (4)10 = (00000000000000000000000000000100)2
After reversing the binary form we get:
(00100000000000000000000000000000)2 = (536870912)10

Input : 7
Output : 3758096384
Explanation:
(7)10 = (00000000000000000000000000000111)2
After reversing the binary form we get:
(11100000000000000000000000000000)2 = (3758096384)10

Here first we will convert the number into binary form in a reverse way and every bit of binary number gets converted into decimal form and added to the previous one.

For input   (5)10  binary form is (00000000000000000000000000000101)2 

                 After reversing (10100000000000000000000000000000)2 

and its decimal form is (2684354560)10

The first bit of reversed binary form is 1 if we count from left to right, which means this bit is set, to find this bit we use the logic to convert a decimal numbers into binary.

Let k be a variable that stores this bit and “i = 0” be the variable of loop and increased by 1 in every iteration to find bits, and “j” be a variable that is used to convert it again in decimal whose initial value is 31 and decreased by 1 in every iteration  

k = (n>>i)&1 where i = 0  and j =31

k = (5>>0) & 1 = 1 since this bit is set then it takes part in converting in the decimal form again,  and it will be dn = dn + 2^31 where dn is new decimal form which is initially 0 and dn is added with all set bits

The second bit is  0.  

k = (n>>i)&1 where i = 1  and j =30

k = (5>>1) & 1 = 0   since this bit is not set then it does not  takes part in converting into decimal form

The third bit is 1

k = (n>>i)&1 where i = 2  and j =29

k = (5>>2)&1 = 1 since this bit is set then it takes part in converting in the decimal form again,  and it will be new decimal form then dn = dn + 2^29

The fourth bit is 0

k = (n>>i)&1 where i = 3  and j =28

k = (5>>3)&1 = 0   since this bit is not set then it does not takes part in converting in decimal form.

and so on…  for every set bit dn is updated until it founds all 32 bits and will be the required answer.

C++




#include <bits/stdc++.h>
using namespace std;
 
// function to reverse and convert in decimal
long long reversedBitsNum(long long n)
{
    long long dn = 0; // variable for new decimal number
    int j = 30; // initial value of j
    // loop to find the reversede binary bit
    for (int i = 0; i < 32; ++i) {
        int k = (n >> i) & 1; // k will be the required bit
        if (k) { // if bit is set then only convert in
                 // decimal
            if (j == -1) { // since if j = -1 then left
                           // shift operator will not work
                dn = abs(dn) + pow(2, 0);
            }
            else {
                dn = abs(dn)
                     + (2 << j); // here left shift operator
                                 // calculates 2 to power j
                                 // for making code efficient
            }
        }
        j--;  // j is decreased in each iteration
    }
  return abs(dn);
}
 
int main()
{
    long long n = 4;
    cout<<"Decimal number after reversing all 32 bits is : "<<reversedBitsNum(n);
    return 0;
}


Java




public class Main {
    // function to reverse and convert in decimal
    public static long reversedBitsNum(long n) {
        long dn = 0; // variable for new decimal number
        int j = 30; // initial value of j
        // loop to find the reversed binary bit
        for (int i = 0; i < 32; i++) {
            int k = (int)((n >> i) & 1); // k will be the required bit
            if (k != 0) { // if bit is set then only convert in decimal
                if (j == -1) { // since if j = -1 then left shift operator will not work
                    dn = Math.abs(dn) + (long)Math.pow(2, 0);
                } else {
                    dn = Math.abs(dn) + (2 << j); // here left shift operator calculates 2 to power j for making code efficient
                }
            }
            j--; // j is decreased in each iteration
        }
        return Math.abs(dn);
    }
 
    public static void main(String[] args) {
        long n = 4;
        System.out.println("Decimal number after reversing all 32 bits is : " + reversedBitsNum(n));
    }
}
 
// This code is contributed by shivhack999


Python3




# python code implementation for the above approach
 
# function to reverse and convert in decimal
 
 
def reversedBitsNum(n):
    dn = 0  # variable for new decimal number
    j = 30  # initial value of j
    # loop to find the reversed binary bit
    for i in range(32):
        k = (n >> i) & 1  # k will be the required bit
        if k != 0:  # if bit is set then only convert in
            # decimal
            if j == -1:  # since if j = -1 then left
                # shift operator will not work
                dn = abs(dn) + pow(2, 0)
 
            else:
                dn = abs(dn) + (2 << j)  # here left shift operator
                # calculates 2 to power j
                # for making code efficient
 
        j = j - 1  # j is decreased in each iteration
    return abs(dn)
 
 
n = 4
print("Decimal number after reversing all 32 bits is : ", reversedBitsNum(n))
 
# This code is contributed by Nidhi goel.


C#




using System;
 
public class GFG
{
   
  // function to reverse and convert in decimal
  public static long reversedBitsNum(long n)
  {
    long dn = 0; // variable for new decimal number
    int j = 30; // initial value of j
    // loop to find the reversed binary bit
    for (int i = 0; i < 32; ++i) {
      int k
        = (int)((n >> i)
                & 1); // k will be the required bit
      if (k != 0) { // if bit is set then only convert
        // in decimal
        if (j
            == -1) { // since if j = -1 then left
          // shift operator will not work
          dn = Math.Abs(dn)
            + (long)Math.Pow(2, 0);
        }
        else {
          dn = Math.Abs(dn)
            + (2
               << j); // here left shift
          // operator calculates 2
          // to power j for making
          // code efficient
        }
      }
      j--; // j is decreased in each iteration
    }
    return Math.Abs(dn);
  }
 
  static public void Main()
  {
    long n = 4;
    Console.WriteLine(
      "Decimal number after reversing all 32 bits is : "
      + reversedBitsNum(n));
  }
}
 
// This code is contributed by akashish__


Javascript




// function to reverse and convert in decimal
function reversedBitsNum(n) {
  let dn = 0; // variable for new decimal number
  let j = 30; // initial value of j
  // loop to find the reversede binary bit
  for (let i = 0; i < 32; ++i) {
    let k = (n >> i) & 1; // k will be the required bit
    if (k) { // if bit is set then only convert in
      // decimal
      if (j == -1) { // since if j = -1 then left
        // shift operator will not work
        dn = Math.abs(dn) + Math.pow(2, 0);
      } else {
        dn = Math.abs(dn) + (2 << j); // here left shift operator
        // calculates 2 to power j
        // for making code efficient
      }
    }
    j--; // j is decreased in each iteration
  }
  return Math.abs(dn);
}
 
let n = 4;
console.log(
  "Decimal number after reversing all 32 bits is : " + reversedBitsNum(n)
);
 
// This code is contributed by akashish__


Output

Decimal number after reversing all 32 bits is : 536870912

In the above program, we use abs(dn) everywhere because when it calculates 2^31 since there can be only 32 bits it gives the negative value of the same magnitude, to correct this we return the absolute value of dn.

Contributed by Shivam Verma(coder_shiv)



Similar Reads

Invert actual bits of a number
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 : 11Output : 4(11)10 = (1011)[2]After inverting the bits, we get:(010
13 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
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
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
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 - Simple: Loop through all the bits of an integer. I
6 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
Reverse bits using lookup table in O(1) time
Given an unsigned integer, reverse all bits of it and return the number with reversed bits. Examples: Input : n = 1 Output : 2147483648 On a machine with size of unsigned bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648 Output : 1 In the previous post we had seen two method that solved this problem in O(n) & O(logn ) time. Her
7 min read
Absolute difference between the count of set bits in N and its reverse
Given an integer N, the task is to find the absolute difference between the number of set bits present in the number N and in reverse of the number N. Examples: Input: N = 13Output: 2Explanation:Binary representation of (13)10 = (1101)2Count of set bits = 3Reverse of 13 is 31Binary representation of (31)10 = (11111)2Count of set bits of reversed nu
7 min read
Count of unique pairs (i, j) in an array such that sum of A[i] and reverse of A[j] is equal to sum of reverse of A[i] and A[j]
Given an array arr[] consisting of N positive integers, the task is to find the count of unique pairs (i, j) such that the sum of arr[i] and the reverse(arr[j]) is the same as the sum of reverse(arr[i]) and arr[j]. Examples: Input: arr[] = {2, 15, 11, 7}Output: 3Explanation:The pairs are (0, 2), (0, 3) and (2, 3). (0, 2): arr[0] + reverse(arr[2]) (
7 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
Reverse and Add given number repeatedly to get a Palindrome number
Write a program that takes number and gives the resulting palindrome (if one exists). If it took more than 1, 000 iterations (additions) or yield a palindrome that is greater than 4, 294, 967, 295, assume that no palindrome exist for the given number. Examples: Input: N = 195 Output: 9339 Input: N = 265 Output: 45254 Input: N = 196 Output: No palin
6 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
Swap bits in a given number
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 PracticeSwap bitsTry It! Method 1 Let p1 and p2 be the two given positions. Example 1 Input: x = 47 (
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
Article Tags :
Practice Tags :