VOOZH about

URL: https://www.geeksforgeeks.org/dsa/reverse-actual-bits-given-number/

⇱ Reverse actual bits of the given number - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Reverse actual bits of the given number

Last Updated : 14 Jan, 2026

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 : 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.

Approach:

 The idea is to build the reversed number by examining each bit of the input number from right to left, while simultaneously constructing the result from left to right using left shift and right shift operators.

Step by step approach:

  1. Traverse each bit of the input number using right shift operations (n >>= 1).
  2. Build the result by shifting it left (ans <<= 1) before each new bit is processed.
  3. When a '1' bit is encountered in the input (n & 1 == 1), set the rightmost bit of the result (ans |= 1).
  4. Continue this process until all bits in the input number have been processed (n > 0).

👁 Image


Output
13

Time Complexity: O(log n)
Space Complexity: O(1)

Comment
Article Tags:
Article Tags: