Write an Efficient C Program to Reverse Bits of a Number
Last Updated :
28 May, 2024
Given an unsigned integer, reverse all bits of it and return the number with reversed bits.
Input : n = 1
Output : 2147483648
Explanation : On a machine with size of unsigned bit as 32. Reverse of 0....001 is 100....0.
Input : n = 2147483648
Output : 1
Method1 - Simple: Loop through all the bits of an integer. If a bit at ith position is set in the i/p no. then set the bit at (NO_OF_BITS - 1) - i in o/p. Where NO_OF_BITS is number of bits present in the given number.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
// Function to reverse bits of num
unsigned int reverseBits(unsigned int num)
{
unsigned int NO_OF_BITS = sizeof(num) * 8;
unsigned int reverse_num = 0;
int i;
for (i = 0; i < NO_OF_BITS; i++) {
if ((num & (1 << i)))
reverse_num |= 1 << ((NO_OF_BITS - 1) - i);
}
return reverse_num;
}
// Driver code
int main()
{
unsigned int x = 2;
cout << reverseBits(x);
return 0;
}
// This code is contributed By Shivam Tiwari
c
// C code to implement the approach
#include <stdio.h>
// Function to reverse bits of num
unsigned int reverseBits(unsigned int num)
{
unsigned int NO_OF_BITS = sizeof(num) * 8;
unsigned int reverse_num = 0;
int i;
for (i = 0; i < NO_OF_BITS; i++) {
if ((num & (1 << i)))
reverse_num |= 1 << ((NO_OF_BITS - 1) - i);
}
return reverse_num;
}
// Driver code
int main()
{
unsigned int x = 2;
printf("%u", reverseBits(x));
getchar();
}
Java
import java.util.*;
public class GFG {
static int reverseBits(int num)
{
int NO_OF_BITS = Integer.SIZE;
int reverse_num = 0;
for (int i = 0; i < NO_OF_BITS; i++) {
if (((num >> i) & 1) == 1)
reverse_num |= 1 << ((NO_OF_BITS - 1) - i);
}
return reverse_num;
}
public static void main(String[] args)
{
int x = 2;
System.out.println(reverseBits(x));
}
}
Python
def reverse_bits(num):
NO_OF_BITS = 32
reverse_num = 0
for i in range(NO_OF_BITS):
if (num & (1 << i)):
reverse_num |= 1 << ((NO_OF_BITS - 1) - i)
return reverse_num
# Driver code
x = 2
print(reverse_bits(x))
C#
using System;
public class GFG {
// Function to reverse bits of num
public static uint ReverseBits(uint num)
{
uint NO_OF_BITS = (uint)(sizeof(uint) * 8);
uint reverse_num = 0;
int i;
for (i = 0; i < NO_OF_BITS; i++) {
if ((num & (1u << i)) != 0)
reverse_num
|= 1u << ((int)(NO_OF_BITS - 1) - i);
}
// Return the reversed number
return reverse_num;
}
// Driver Code
public static void Main()
{
uint x = 2u;
Console.WriteLine(ReverseBits(x));
}
}
JavaScript
function reverseBits(num) {
let NO_OF_BITS = 32;
let reverse_num = 0;
for (let i = 0; i < NO_OF_BITS; i++) {
if ((num & (1 << i)) !== 0) {
reverse_num |= 1 << (NO_OF_BITS - 1) - i;
}
}
return reverse_num;
}
// Driver code
let x = 2;
console.log(reverseBits(x));
Time Complexity: O(Log n). Time complexity would be Log(num) as there are log(num) bits in a binary number "num" and we're looping through all bits.
Auxiliary space: O(1)
Method 2 - Standard: The idea is to keep putting set bits of the num in reverse_num until num becomes zero. After num becomes zero, shift the remaining bits of reverse_num. Let num is stored using 8 bits and num be 00000110. After the loop you will get reverse_num as 00000011. Now you need to left shift reverse_num 5 more times and you get the exact reverse 01100000.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
// Function to reverse bits of num
unsigned int reverseBits(unsigned int num)
{
unsigned int count = sizeof(num) * 8 - 1;
unsigned int reverse_num = num;
num >>= 1;
while (num) {
reverse_num <<= 1;
reverse_num |= num & 1;
num >>= 1;
count--;
}
reverse_num <<= count;
return reverse_num;
}
// Driver's code
int main()
{
unsigned int x = 1;
cout << reverseBits(x) << endl;
return 0;
}
// This code is contributed By Shivam Tiwari
C
// C code to implement the approach
#include <stdio.h>
// Function to reverse bits of num
unsigned int reverseBits(unsigned int num)
{
unsigned int count = sizeof(num) * 8 - 1;
unsigned int reverse_num = num;
num >>= 1;
while (num) {
reverse_num <<= 1;
reverse_num |= num & 1;
num >>= 1;
count--;
}
reverse_num <<= count;
return reverse_num;
}
// Driver's code
int main()
{
unsigned int x = 1;
printf("%u", reverseBits(x));
getchar();
}
Java
public class Main {
// Function to reverse bits of num
static int reverseBits(int num) {
int count = 32 - 1;
int reverseNum = num;
num >>= 1;
while (num != 0) {
reverseNum <<= 1;
reverseNum |= num & 1;
num >>= 1;
count--;
}
reverseNum <<= count;
return reverseNum;
}
public static void main(String[] args) {
int x = 1;
System.out.println(reverseBits(x));
}
}
Python
def reverseBits(num):
count = 32 - 1
reverse_num = num
num >>= 1
while (num):
reverse_num <<= 1
reverse_num |= num & 1
num >>= 1
count -= 1
reverse_num <<= count
return reverse_num
# Driver's code
if __name__ == '__main__':
x = 1
print(reverseBits(x))
# This code is contributed by shivhack999
C#
using System;
class Program
{
// Function to reverse bits of num
static uint ReverseBits(uint num)
{
uint count = sizeof(uint) * 8 - 1;
uint reverse_num = num;
num >>= 1;
while (num != 0)
{
reverse_num <<= 1;
reverse_num |= num & 1;
num >>= 1;
count--;
}
reverse_num <<= (int)count;
return reverse_num;
}
// Driver's code
static void Main()
{
uint x = 1;
Console.WriteLine(ReverseBits(x));
}
}
// This Code is Contributed by Shivam Tiwari
JavaScript
// Javascript code to implement the approach
// Function to reverse bits of num
function reverseBits(num) {
let count = 32;
let reverseNum = 0;
while (num) {
reverseNum = (reverseNum << 1) | (num & 1);
num >>>= 1;
count--;
}
reverseNum <<= count;
return reverseNum >>> 0; // Convert back to unsigned 32-bit integer
}
// Driver's code
let x = 1;
console.log(reverseBits(x));
// This code is contributed by Taranpreet Singh.
Time Complexity: O(logn) where n is the given number
Auxiliary space: O(1)
Method 3 - Lookup Table: We can reverse the bits of a number in O(1) if we know the size of the number. We can implement it using look up table. Please refer Reverse bits using lookup table in O(1) time for details.
Source : https://graphics.stanford.edu/~seander/bithacks.html
Similar Reads
Write a program to reverse digits of a number Given an Integer n, find the reverse of its digits.Examples: Input: n = 122Output: 221Explanation: By reversing the digits of number, number will change into 221.Input: n = 200Output: 2Explanation: By reversing the digits of number, number will change into 2.Input: n = 12345 Output: 54321Explanation
8 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.I
11 min read
Reverse actual bits of the given number Given a non-negative integer n, the task is to reverse the bits in its binary representation and return the resulting decimal number. The reversal should consider only the actual binary digits without any leading zeros.Examples : Input : 11Output : 13Explanation: (11)10 = (1011)2.After reversing the
4 min read
Reverse digits of an integer with overflow handled | Set 2 Given a 32-bit integer N. The task is to reverse N, if the reversed integer overflows, print -1 as the output. Examples Input: N = 123Output: 321 Input: N = -123Output: -321 Input: N = 120Output: 21 Approach: Unlike approaches Set 1 of the article, this problem can be solved simply by using a 64-bit
9 min read
Reverse bits of a positive integer number in Python Given an positive integer and size of bits, reverse all bits of it and return the number with reversed bits.Examples: Input : n = 1, bitSize=32 Output : 2147483648 On a machine with size of bit as 32. Reverse of 0....001 is 100....0. Input : n = 2147483648, bitSize=32 Output : 1 We can solve this pr
4 min read
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