Tutorialspoint
Problem
Solution
Submissions

Reverse Bits of an Integer

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a C program to reverse the bits of a given 32-bit unsigned integer. The program should return the integer obtained after reversing the bits.

Example 1
  • Input: n = 43261596 (represented in binary as 00000010100101000001111010011100)
  • Output: 964176192 (represented in binary as 00111001011110000010100101000000)
  • Explanation: The binary representation of 43261596 is 00000010100101000001111010011100.
    Reversing all bits gives 00111001011110000010100101000000.
    The decimal value of 00111001011110000010100101000000 is 964176192.
Example 2
  • Input: n = 4294967293 (represented in binary as 11111111111111111111111111111101)
  • Output: 3221225471 (represented in binary as 10111111111111111111111111111111)
  • Explanation: The binary representation of 4294967293 is 11111111111111111111111111111101.
    Reversing all bits gives 10111111111111111111111111111111.
    The decimal value of 10111111111111111111111111111111 is 3221225471.
Constraints
  • The input must be a 32-bit unsigned integer.
  • You need to handle the entire 32-bit number, even leading zeros.
  • Time Complexity: O(1) - because we're dealing with a fixed-size integer (32 bits).
  • Space Complexity: O(1) - only using a constant amount of extra space.
NumberSamsungArctwist
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Initialize a result variable to 0.
  • Iterate through all 32 bits of the input integer.
  • For each bit position, check if the corresponding bit in the input is set (1).
  • If the bit is set, set the corresponding bit in the reversed position of the result.
  • Return the final result after processing all 32 bits.
  • Be careful about bit shifting operations and data types.
  • Consider using bitwise operations like left shift (<<), right shift (>>), and bitwise AND (&).

Steps to solve by this approach:

 Step 1: Initialize a result variable to 0 to store our reversed number.

 Step 2: Loop through all 32 bits of the input number.
 Step 3: For each iteration, left shift the result by 1 to make room for the next bit.
 Step 4: Check if the least significant bit of n is 1 using bitwise AND operation (n & 1).
 Step 5: If it's 1, set the least significant bit of result to 1 using bitwise OR operation (result |= 1).
 Step 6: Right shift n by 1 to process the next bit.
 Step 7: After 32 iterations, return the final result.

Submitted Code :