Learner Level

Implement the reverseBitsSimple method that returns the integer formed after reversing the bits.

The input is a positive integer n.

Your task is to reverse the bits in its binary representation and return the decimal value of the reversed binary number. Leading zeros after reversal do not affect the decimal result.

For example, 13 is binary 1101. Reversing it gives 1011, which is decimal 11.

Example 1

Input
n (int) = 13
Returns (int) 11

Example 2

Input
n (int) = 10
Returns (int) 5

Example 3

Input
n (int) = 8
Returns (int) 1

Build the reversed number one bit at a time.

Repeatedly take the last bit of n using n % 2. Before adding that bit to the answer, shift the answer left by one position. Then remove the last bit from n by dividing it by two.

When all bits are processed, the answer contains the reversed binary value.

Pseudocode:

function reverseBitsSimple(n):
    result = 0
    while n > 0:
        bit = n % 2
        result = result * 2 + bit
        n = n / 2
    return result
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.