VOOZH about

URL: https://www.geeksforgeeks.org/dsa/write-an-efficient-c-program-to-reverse-bits-of-a-number/

⇱ Write an Efficient C Program to Reverse Bits of a Number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Write an Efficient C Program to Reverse Bits of a Number

Last Updated : 23 Jul, 2025

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                            

Recommended Practice

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:


Output
1073741824

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_num5 more times and you get the exact reverse01100000.

Below is the implementation of the above approach:


Output
2147483648

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

Comment