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.
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++
#include <bits/stdc++.h>
using namespace std;
unsigned int reverseBits(unsigned int n)
{
unsigned int rev = 0;
while (n > 0) {
rev <<= 1;
if (n & 1 == 1)
rev ^= 1;
n >>= 1;
}
return rev;
}
int main()
{
unsigned int n = 11;
cout << reverseBits(n);
return 0;
}
|
C
#include <stdio.h>
unsigned int reverseBits(unsigned int n)
{
unsigned int rev = 0;
while (n > 0) {
rev <<= 1;
if (n & 1 == 1)
rev ^= 1;
n >>= 1;
}
return rev;
}
int main()
{
unsigned int n = 11;
printf("%u", reverseBits(n));
return 0;
}
|
Java
import java.io.*;
class GFG {
public static int reverseBits(int n)
{
int rev = 0;
while (n > 0) {
rev <<= 1;
if ((int)(n & 1) == 1)
rev ^= 1;
n >>= 1;
}
return rev;
}
public static void main(String[] args)
{
int n = 11;
System.out.println(reverseBits(n));
}
}
|
Python3
def reverseBits(n):
rev = 0
while (n > 0):
rev = rev << 1
if (n & 1 == 1):
rev = rev ^ 1
n = n >> 1
return rev
n = 11
print(reverseBits(n))
|
C#
using System;
class GFG {
public static int reverseBits(int n)
{
int rev = 0;
while (n > 0) {
rev <<= 1;
if ((int)(n & 1) == 1)
rev ^= 1;
n >>= 1;
}
return rev;
}
public static void Main()
{
int n = 11;
Console.WriteLine(reverseBits(n));
}
}
|
PHP
<?php
function reverseBits($n)
{
$rev = 0;
while ($n > 0)
{
$rev <<= 1;
if ($n & 1 == 1)
$rev ^= 1;
$n >>= 1;
}
return $rev;
}
$n = 11;
echo reverseBits($n);
?>
|
Javascript
<script>
function reverseBits(n)
{
let rev = 0;
while (n > 0)
{
rev <<= 1;
if ((n & 1) == 1)
rev ^= 1;
n >>= 1;
}
return rev;
}
let n = 11;
document.write(reverseBits(n));
</script>
|
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;
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;
showBits(num);
int ret = reverseBits(num);
cout << "\nreverse of number " << num << " is=" << ret << endl;
showBits(ret);
cout << "\n";
num = -10;
showBits(num);
ret = reverseBits(num);
cout << "\nreverse of number " << num << " is=" << ret << endl;
showBits(ret);
return 0;
}
|
Java
import java.io.*;
import java.util.List;
import java.util.ArrayList;
class ReverseBits190 {
public static void main (String[] args) {
int num = 11;
showBits(num);
int ret = reverseBits(num);
System.out.println("\nreverse of number " + num + " is=" + ret);
showBits(ret);
System.out.println("\n");
num = -10;
showBits(num);
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;
}
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;
ShowBits(num);
int ret = ReverseBits(num);
Console.WriteLine("\nreverse of number " + num + " is=" + ret);
ShowBits(ret);
Console.WriteLine("\n");
num = -10;
ShowBits(num);
ret = ReverseBits(num);
Console.WriteLine("\nreverse of number " + num + " is=" + ret);
ShowBits(ret);
}
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;
}
}
|
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
show_bits(num)
ret = reverse_bits(num)
print("reverse of number", num, "is=", ret)
show_bits(ret)
print()
num = -10
show_bits(num)
ret = reverse_bits(num)
print("reverse of number", num, "is=", ret)
show_bits(ret)
|
Javascript
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;
showBits(num);
let ret = reverseBits(num);
console.log('reverse of number ${num} is= ${ret}');
showBits(ret);
console.log();
num = -10;
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;
long long reversedBitsNum(long long n)
{
long long dn = 0;
int j = 30;
for (int i = 0; i < 32; ++i) {
int k = (n >> i) & 1;
if (k) {
if (j == -1) {
dn = abs(dn) + pow(2, 0);
}
else {
dn = abs(dn)
+ (2 << j);
}
}
j--;
}
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 {
public static long reversedBitsNum(long n) {
long dn = 0;
int j = 30;
for (int i = 0; i < 32; i++) {
int k = (int)((n >> i) & 1);
if (k != 0) {
if (j == -1) {
dn = Math.abs(dn) + (long)Math.pow(2, 0);
} else {
dn = Math.abs(dn) + (2 << j);
}
}
j--;
}
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));
}
}
|
Python3
def reversedBitsNum(n):
dn = 0
j = 30
for i in range(32):
k = (n >> i) & 1
if k != 0:
if j == -1:
dn = abs(dn) + pow(2, 0)
else:
dn = abs(dn) + (2 << j)
j = j - 1
return abs(dn)
n = 4
print("Decimal number after reversing all 32 bits is : ", reversedBitsNum(n))
|
C#
using System;
public class GFG
{
public static long reversedBitsNum(long n)
{
long dn = 0;
int j = 30;
for (int i = 0; i < 32; ++i) {
int k
= (int)((n >> i)
& 1);
if (k != 0) {
if (j
== -1) {
dn = Math.Abs(dn)
+ (long)Math.Pow(2, 0);
}
else {
dn = Math.Abs(dn)
+ (2
<< j);
}
}
j--;
}
return Math.Abs(dn);
}
static public void Main()
{
long n = 4;
Console.WriteLine(
"Decimal number after reversing all 32 bits is : "
+ reversedBitsNum(n));
}
}
|
Javascript
function reversedBitsNum(n) {
let dn = 0;
let j = 30;
for (let i = 0; i < 32; ++i) {
let k = (n >> i) & 1;
if (k) {
if (j == -1) {
dn = Math.abs(dn) + Math.pow(2, 0);
} else {
dn = Math.abs(dn) + (2 << j);
}
}
j--;
}
return Math.abs(dn);
}
let n = 4;
console.log(
"Decimal number after reversing all 32 bits is : " + reversedBitsNum(n)
);
|
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
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 : 13Ex
15+ min read
Set all the bits in given range of a number
Given a non-negative number n and two values l and r. The problem is to set the bits in the range l to r in the binary representation of n, i.e, to unset bits from the rightmost lth bit to the rightmost r-th bit. Constraint: 1 <= l <= r <= number of bits in the binary representation of n.Ex
5 min read
Set the K-th bit of a given number
Given a number n and a value k. From the right, set the kth bit in the binary representation of n. The position of LSB(or last bit) is 0, second last bit is 1 and so on. Also, 0 <= k < x, where x is the number of bits in the binary representation of n.Examples: Input : n = 10, k = 2 Output : 1
4 min read
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)1
13 min read
Binary representation of a given number
Write a program to print a Binary representation of a given number. Source: Microsoft Interview Set-3 Method 1: Iterative Method: For any number, we can check whether its 'i'th bit is 0(OFF) or 1(ON) by bitwise AND it with "2^i" (2 raise to i). 1) Let us take number 'NUM' and we want to check whethe
7 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 -
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 (111111111
3 min read
Reverse bytes of a Hexadecimal Number
Given an unsigned integer N. The task is to reverse all bytes of N without using a temporary variable and print the reversed number. Examples: Input: N = 0xaabbccdd Output: 0xddccbbaa Input: N = 0xa912cbd4 Output: 0xd4cb12a9 The naive approach is to extract the appropriate byte is to use mask(&)
4 min read
Set all odd bits of a number
Given a number, the task is to set all odd bits of a number. Positions of bits are counted from LSB (least significant bit) to MSB (Most significant bit). Position of LSB is considered as 1. Examples : Input : 20 Output : 21 Explanation : Binary representation of 20 is 10100. Setting all odd bits ma
15+ min read
Count unset bits of a number
Given a number n, count unset bits after MSB (Most Significant Bit).Examples : Input : 17 Output : 3 Binary of 17 is 10001 so unset bit is 3 Input : 7 Output : 0 A Simple Solution is to traverse through all bits and count unset bits. C/C++ Code // C++ program to count unset bits in an integer #inclu
7 min read