Given an unsigned integer, reverse all bits of it and return the number with reversed bits.
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
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.
Above program can be optimized by removing the use of variable temp. See below the modified code.
Time Complexity: O(n)
Space Complexity: 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.
Time Complexity: O(log n)
Space Complexity: 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.
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Write a program to reverse digits of a number
- Write an Efficient Method to Check if a Number is Multiple of 3
- Write a program to reverse an array or string
- Reverse actual bits of the given number
- Efficient program to print the number of factors of n numbers
- Efficient program to print all prime factors of a given number
- Program to find the Nth natural number with exactly two bits set
- Program to count number of set bits in an (big) array
- Program to invert bits of a number Efficiently
- Reverse bits using lookup table in O(1) time
- Efficient program to calculate e^x
- Efficient Program to Compute Sum of Series 1/1! + 1/2! + 1/3! + 1/4! + .. + 1/n!
- Check if bits of a number has count of consecutive set bits in increasing order
- Toggle bits of a number except first and last bits
- An efficient way to check whether n-th Fibonacci number is multiple of 10
- Check if a given number is Pronic | Efficient Approach
- Space efficient iterative method to Fibonacci number
- Write a program to calculate pow(x,n)
- Write a program to add two numbers in base 14
- Write a program to print all permutations of a given string
Improved By : oyemohit