Problem 190

Abstract / Summary

Reverse the bits of a given 32-bit unsigned integer and return the resulting integer.

Note

The full problem description, including helpful examples, can be found on LeetCode.

C++ 0190.cpp

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {
        uint32_t result = 0;
        for (int i = 0; i < 32; i++)
            if (n & (1 << i))
                result |= 1 << (31 - i);

        return result;
    }
};
11 lines | 245 bytes | submitted August 8, 2023 | GitHub   tab size 4

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 69% (2+ million submissions).

Typical patterns to solve this problem:
  • Bit Manipulation
  • Divide And Conquer
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided Solution class implements a method named reverseBits that takes a 32-bit unsigned integer n and returns a new unsigned integer whose binary representation is the bitwise reversal of n. In other words, the most significant bit of the input becomes the least significant bit of the output, the second most significant becomes the second least significant, and so on for all 32 positions.

Key Steps

The algorithm proceeds in three distinct phases: preparation of the accumulator, per-bit examination and relocation, and final return.

The first phase creates a zero-initialized accumulator that will hold the reversed result.

uint32_t result = 0;

The second phase iterates exactly 32 times, once for each bit position in a 32-bit word. For each iteration index i, the code checks whether the i-th bit of n is set. The test uses a left shift of the constant 1 by i positions and a bitwise AND with n.

for (int i = 0; i < 32; i++)
    if (n & (1 << i))
        result |= 1 << (31 - i);

If the test evaluates to true, the corresponding bit in the result is set. The target position is computed as 31 - i, which mirrors the original index across the midpoint of the 32-bit range. The setting operation uses a bitwise OR to combine the existing result value with a single-bit mask positioned at 31 - i.

The final phase simply returns the accumulated value.

return result;

Edge Cases Handled

When the input n is zero, every iteration of the loop finds the condition n & (1 << i) false, leaving result unchanged at its initial zero value. The function therefore correctly returns zero, which is the bitwise reversal of an all-zero pattern.

If n consists entirely of ones (i.e., 0xFFFFFFFF), each iteration finds the condition true, and the corresponding mirrored bit in result is set. Because every bit is set in both the original and reversed positions, the output again equals 0xFFFFFFFF. This demonstrates that the algorithm correctly handles the maximal unsigned value.

Values with a single set bit, such as 0x00000001 or 0x80000000, are also processed accurately. The loop identifies the lone set bit, computes its mirrored index, and places a single set bit at the opposite end of the 32-bit word, yielding 0x80000000 and 0x00000001 respectively.

Performance Optimizations

The implementation relies exclusively on primitive bitwise operations (&, |, <<) and a fixed-size loop that iterates exactly 32 times regardless of the input. This deterministic iteration count eliminates any data-dependent branching overhead beyond the single conditional inside the loop, which the processor can efficiently predict.

By using a single accumulator (result) and updating it in place, the code avoids the allocation of auxiliary structures or temporary arrays. The shift amounts are computed directly from the loop index, avoiding any function calls or table lookups. Consequently, the method executes with minimal instruction count and low latency on typical CPUs, making it well-suited for performance-critical contexts where bit reversal is required repeatedly.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a row of thirty-two little light bulbs standing in a line. Some are turned on and some are turned off, and this whole row represents a number. This code is like a helper holding a brand new row of thirty-two light bulbs, all of which are turned off and waiting for instructions. The computer looks at the first light bulb in the original row. If that light is on, the helper turns on the very last light in the new row. If the second light in the original row is on, the helper turns on the second to last light in the new row. This continues all the way across until the helper has finished looking at every single light. By doing this, the helper creates a perfect mirror image of your original row of lights, flipping the whole pattern backward from start to finish.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 7 | μ = 7.26 | σ = 0.97

Complexity Analysis

Time: constant
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Python Java TS
WalkCCC C++ Python Java
leetcode.ca C++ Python Java JS Go Rust TS
LeetcodeHelp C++ Python Java
MemoryLimitExceeded C++ Python
Progiez C++ Python Java
github begeekmyfriend C
BigEggStudy C#
black-shadows C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim C
everthis JS
fartem Ruby
FelixFan1122 C#
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JS
keineahnung2345 C++
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
withaarzoo C++
XiaotaoGuo C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, JavaScript, Python, Rust, TypeScript
LeetcodeHelp C++, Java, Python
MemoryLimitExceeded Python, C++
Progiez C++, Java, Python
begeekmyfriend C
BigEggStudy C#
black-shadows C++, C++
chandansgowda Python
charles-wangkai Java
chenyanzhe C++
Dijkstra-Edu Java
DimitrisJim C
everthis JavaScript
fartem Ruby
FelixFan1122 C#
gaosq0604 Python
Garvit244 Python
halfrost Go
haoel C++
JoshCrozier JavaScript
keineahnung2345 C++
Krazune C
lennylxx C
linouk23 C++
lkwq007 Python
luangong C++
shreymehul C#
sonugiri1043 C++
suxrobGM C#
trung-hn Python
varunu28 Java
vli02 C
vthwang Java
withaarzoo C++
XiaotaoGuo C++
53 links | 37 authors | 10 languages

Videos

These are a few popular YouTube videos for this problem:
YouTube video 'Reverse Bits - Binary - Leetcode 190 - Python'
NeetCode 11 mins
Reverse Bits - Binary - Leetcode 190 - Python
YouTube video 'Reverse Bits | LeetCode 190 | C++, Java, Python'
Knowledge Center 23 mins
Reverse Bits | LeetCode 190 | C++, Java, Python
YouTube video 'reverse bits | reverse bits leetcode java | leetcode 190 | bitwise | 1 liner'
Naresh Gupta 7 mins
reverse bits | reverse bits leetcode java | leetcode 190 | bitwise | 1 liner
YouTube video 'Reverse bits | Leet code 190| Theory explained + Python code | July leet code'
Sai Anish Malla 7 mins
Reverse bits | Leet code 190| Theory explained + Python code | July leet code
YouTube video 'Reverse Bits - LeetCode 190 - Python'
Deepti Talesra 10 mins
Reverse Bits - LeetCode 190 - Python
YouTube video 'Google Coding Interview Question - Reverse Bits - LeetCode 190'
AlgoJS 5 mins
Google Coding Interview Question - Reverse Bits - LeetCode 190
YouTube video 'Reverse Bits | Day 12 Bit Masking | [ July LeetCoding Challenge ] [ Leetcode #190 ] [ 2020 ]'
Algorithms Made Easy 5 mins
Reverse Bits | Day 12 Bit Masking | [ July LeetCoding Challenge ] [ Leetcode #190 ] [ 2020 ]
YouTube video 'Reverse Bits - LeetCode #190 - C++'
Sean Chuah 7 mins
Reverse Bits - LeetCode #190 - C++
YouTube video 'Reverse Bits | LeetCode 190 | Java Code | Developer Coder'
Developer Coder 9 mins
Reverse Bits | LeetCode 190 | Java Code | Developer Coder
YouTube video 'Reverse Bits Explained in Telugu | Leetcode 190 | Python DSA | srkcodes'
Srk Codes 10 mins
Reverse Bits Explained in Telugu | Leetcode 190 | Python DSA | srkcodes
YouTube video 'Daily Leetcode #103: Jul 12, 2020 - 190. Reverse Bits'
Programming Live with Larry 4 mins
Daily Leetcode #103: Jul 12, 2020 - 190. Reverse Bits
YouTube video 'Reverse Bits | LeetCode 190 - Python'
impoldev 6 mins
Reverse Bits | LeetCode 190 - Python
YouTube video 'Reverse Bits - Leetcode 190 | Bitwise manipulation'
Code With K5KC 11 mins
Reverse Bits - Leetcode 190 | Bitwise manipulation
YouTube video '178. Leetcode 190. Reverse Bits : JAVA'
Web Fusion with Bharadwaj 13 mins
178. Leetcode 190. Reverse Bits : JAVA
YouTube video 'Reverse Bits - Leetcode 190 - Python'
Tim Huang 5 mins
Reverse Bits - Leetcode 190 - Python
YouTube video 'Reverse Bits | Leetcode 190 | Approach + Code with explanation.'
Pirai's Academy 11 mins
Reverse Bits | Leetcode 190 | Approach + Code with explanation.
YouTube video '145. Leetcode 190. Reverse Bits : Javascript'
Web Fusion with Bharadwaj 16 mins
145. Leetcode 190. Reverse Bits : Javascript
YouTube video 'Day 276:  LeetCode Problem 190. Reverse Bits - Swift'
iOSxBank 8 mins
Day 276: LeetCode Problem 190. Reverse Bits - Swift
YouTube video '190. Reverse Bits| Reverse Bits |Must do Bit Manipulation DSA| Leetcode 190| Bit Manipulation'
Code Thoughts 11 mins
190. Reverse Bits| Reverse Bits |Must do Bit Manipulation DSA| Leetcode 190| Bit Manipulation
YouTube video '190. Reverse Bits (Bit Manipulation) | Leetcode | Python'
Abdullah Arshed 3 mins
190. Reverse Bits (Bit Manipulation) | Leetcode | Python
20 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

3 similar problems

Solved On The Same Day

18 easy 43 medium 2 hard
64 solutions   August 8, 2023

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality