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;
}
};
Difficulty
and has an acceptance rate of about 69% (2+ million submissions).
Typical patterns to solve this problem:
- Bit Manipulation
- Divide And Conquer
AI Disclaimer
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.
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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Similar Problems
- problem 7: Reverse Integer
- problem 191: Number of 1 Bits
- problem 2119: A Number After a Double Reversal
Solved On The Same Day
- problem 1: Two Sum
- problem 9: Palindrome Number
- problem 14: Longest Common Prefix
- problem 20: Valid Parentheses
- problem 26: Remove Duplicates from Sorted Array
- problem 27: Remove Element
- problem 83: Remove Duplicates from Sorted List
- problem 88: Merge Sorted Array
- problem 94: Binary Tree Inorder Traversal
- problem 100: Same Tree
- problem 104: Maximum Depth of Binary Tree
- problem 121: Best Time to Buy and Sell Stock
- problem 136: Single Number
- problem 141: Linked List Cycle
- problem 169: Majority Element
- problem 226: Invert Binary Tree
- problem 234: Palindrome Linked List
- problem 1114: Print in Order
- problem 3: Longest Substring Without Repeating Characters
- problem 7: Reverse Integer
- problem 8: String to Integer (atoi)
- problem 11: Container With Most Water
- problem 12: Integer to Roman
- problem 15: 3Sum
- problem 17: Letter Combinations of a Phone Number
- problem 22: Generate Parentheses
- problem 31: Next Permutation
- problem 36: Valid Sudoku
- problem 39: Combination Sum
- problem 40: Combination Sum II
- problem 45: Jump Game II
- problem 46: Permutations
- problem 47: Permutations II
- problem 48: Rotate Image
- problem 49: Group Anagrams
- problem 55: Jump Game
- problem 59: Spiral Matrix II
- problem 75: Sort Colors
- problem 77: Combinations
- problem 91: Decode Ways
- problem 95: Unique Binary Search Trees II
- problem 96: Unique Binary Search Trees
- problem 134: Gas Station
- problem 164: Maximum Gap
- problem 189: Rotate Array
- problem 215: Kth Largest Element in an Array
- problem 238: Product of Array Except Self
- problem 287: Find the Duplicate Number
- problem 322: Coin Change
- problem 347: Top K Frequent Elements
- problem 377: Combination Sum IV
- problem 438: Find All Anagrams in a String
- problem 474: Ones and Zeroes
- problem 518: Coin Change II
- problem 526: Beautiful Arrangement
- problem 763: Partition Labels
- problem 983: Minimum Cost For Tickets
- problem 994: Rotting Oranges
- problem 1027: Longest Arithmetic Subsequence
- problem 2140: Solving Questions With Brainpower
- problem 2466: Count Ways To Build Good Strings
- problem 4: Median of Two Sorted Arrays
- problem 41: First Missing Positive
Extra
- 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