15% off all plans & roadmaps Use code
See plansReverse Bits
Updated
TL;DR: Reverse the order of all 32 bits of an integer, including leading zeros, and return the result as a signed 32-bit value. The fastest method swaps halves of the word with masks in 5 steps. The common 32-step shift loop is also fine.
Problem
You are given a signed 32-bit integer n. Treat it as a fixed-width 32-bit two's-complement pattern. Bit 31 is the sign bit, bits 30 through 0 hold the rest of the value, and leading zero bits count as part of the pattern.
Reverse the order of all 32 bits. The bit at position 0 moves to position 31, the bit at position 1 moves to position 30, and so on. Read the new 32-bit pattern as a signed two's-complement integer and return it.
Implement Solution.reverseBits(n). Both the input and the returned value are signed 32-bit integers.
Example 1
Input: n = 1 Output: -2147483648 Explanation: The pattern for 1 has only its lowest bit set. After reversal that bit sits at position 31, which stands for -2^31 in a signed 32-bit integer.
Example 2
Input: n = 5 Output: -1610612736 Explanation: The set bits of 5 are at positions 0 and 2. They move to positions 31 and 29, which gives the signed value -1610612736.
Example 3
Input: n = -2 Output: 2147483647 Explanation: The pattern for -2 is all ones except the lowest bit. Reversed, bit 31 is clear and every lower bit is set, which equals 2147483647.
Constraints
-2^31 <= n <= 2^31 - 1nis an integernis represented with exactly 32 bits, including leading zero bits- The returned value is read as a signed 32-bit two's-complement integer
-2^31 <= returned value <= 2^31 - 1
Constraints that matter
- The width is fixed at 32 bits, so every approach does a constant amount of work. Even a 32-iteration loop counts as O(1), and speed differences come down to constant factors.
- Leading zeros are part of the pattern. Any method that stops when the number reaches zero, or that uses a variable-length binary string, produces wrong positions.
- Input and output are signed. Negative inputs must be read by their two's-complement pattern, and a result with bit 31 set must come back negative.
- The value range is exactly 32 bits, so Java, C# and C++ need unsigned or logical shifts, and Python and JavaScript need explicit masking or conversion.
Hints
Hint 1
This is a bit manipulation problem with a fixed word size.
Hint 2
Write the 32-bit pattern of n as a string of exactly 32 characters, reverse the string, and parse it back as a base-2 number.
Solution
Intuition
This is a bit manipulation problem with a fixed word size. The statement says the input has exactly 32 bits, leading zeros included. That tells you to think in positions 0 through 31, never in terms of the number's value or its binary string length.
Picture a shelf of 32 boxes flipped end to end by cutting it in halves, swapping the halves, and repeating inside each half. Each mask pair does one such cut-and-swap pass across the whole word, so five passes replace 32 single moves.
Two moves cover everything you need. n & 1 reads the lowest bit, and shifting moves bits sideways. Read bits from the low end of the input and push each one onto the low end of a new number after shifting it left. The first bit read ends up at the top, and after 32 rounds the order is reversed.
There is a second view. A bit at position p must land at position 31 - p. Since 31 is 11111 in binary, 31 - p is the same as flipping all five bits of the position number p. Swapping the two 16-bit halves flips the top bit of every position number. Swapping adjacent bytes inside each half flips the next one, and so on down to swapping adjacent single bits. Five masked swaps give the same answer as 32 loop rounds.
The last detail is the sign. Languages with fixed 32-bit integers (Java, C#, C++, Go with int32) give you the signed reading for free once the bit pattern is right. Python integers have no fixed width. There you mask the input to 32 bits and subtract 2^32 at the end if bit 31 is set.
Worked example
Input: n = -2147483648 Output: 1 Explanation: The input -2147483648 has only bit 31 set, so its pattern is 1 followed by 31 zeros. Reversing the order moves that single set bit to position 0. The result is 0...01, which is 1. The input and output are mirror images of Example 1.
Approach 1: Binary string, reverse, parse
Write the 32-bit pattern of n as a string of exactly 32 characters, reverse the string, and parse it back as a base-2 number. This is how most people first solve it, because the problem reads like a string reversal.
The only real work is getting a faithful 32-character string. Plain binary conversion drops leading zeros and may print a minus sign for negatives. You must pad to 32 characters and take the bits of the unsigned pattern. The parsed value must then be read as signed.
Steps
- Take the low 32 bits of
nas an unsigned pattern. - Build a string of 32 characters, one per bit, from bit 31 down to bit 0.
- Reverse the string.
- Parse the reversed string as a base-2 number.
- If the parsed value is 2^31 or more, subtract 2^32 (or use an unsigned-to-signed conversion).
- Return the signed value.
Dry run
Input n = -2147483648. Its unsigned pattern is 0x80000000.
- The 32-character string is
1followed by 31 zeros. - Reversed, it is 31 zeros followed by
1. - Parsed in base 2, that is the value 1.
- 1 is below 2^31, so no sign adjustment is needed. The answer is 1.
Complexity
| Time | O(1) |
|---|---|
| Space | O(1) |
The string always has exactly 32 characters, so building it, reversing it, and parsing it each take a fixed 32 steps. The string uses 32 characters of memory no matter what n is. The constants are larger than for pure bit work because of allocation and parsing.
PythonTested in our runner
from typing import List, Optional
class Solution:
def reverseBits(self, n: int) -> int:
# 32-character pattern of the unsigned value, leading zeros kept
bits = format(n & 0xFFFFFFFF, '032b')
value = int(bits[::-1], 2)
# read the pattern as signed
if value >= 1 << 31:
value -= 1 << 32
return valueJavaTested in our runner
import java.util.*;
class Solution {
public int reverseBits(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 31; i >= 0; i--) {
sb.append((n >>> i) & 1);
}
sb.reverse();
// parseUnsignedInt keeps the 32-bit pattern, so bit 31 becomes the sign
return Integer.parseUnsignedInt(sb.toString(), 2);
}
}C++Tested in our runner
#include <string>
#include <algorithm>
class Solution {
public:
int reverseBits(int n) {
unsigned int u = static_cast<unsigned int>(n);
std::string s;
for (int i = 31; i >= 0; --i) {
s += ((u >> i) & 1u) ? '1' : '0';
}
std::reverse(s.begin(), s.end());
unsigned int value = static_cast<unsigned int>(std::stoul(s, nullptr, 2));
return static_cast<int>(value);
}
};JavaScriptTested in our runner
/**
* @param {number} n
* @return {number}
*/
var reverseBits = function(n) {
// >>> 0 gives the unsigned 32-bit value, padStart keeps leading zeros
const bits = (n >>> 0).toString(2).padStart(32, '0');
const reversed = bits.split('').reverse().join('');
// | 0 wraps the unsigned result into the signed range
return parseInt(reversed, 2) | 0;
};GoTested in our runner
import "strconv"
func reverseBits(n int) int {
u := uint32(n)
s := make([]byte, 32)
for i := 0; i < 32; i++ {
s[31-i] = byte('0' + (u>>uint(i))&1)
}
for l, r := 0, 31; l < r; l, r = l+1, r-1 {
s[l], s[r] = s[r], s[l]
}
v, _ := strconv.ParseUint(string(s), 2, 32)
return int(int32(uint32(v)))
}C#Tested in our runner
public class Solution {
public int reverseBits(int n) {
// Convert.ToString on a negative int prints its 32-bit pattern
char[] bits = Convert.ToString(n, 2).PadLeft(32, '0').ToCharArray();
Array.Reverse(bits);
return unchecked((int)Convert.ToUInt32(new string(bits), 2));
}
}Approach 2: Shift loop, 32 rounds
What's slow: the string version allocates text, reverses it, and parses it, only to move 32 bits around. It also hides the sign and padding traps inside library calls.
The insight that fixes it: work on the bits directly. Read the lowest bit of the input with n & 1, shift the result left, and push the bit onto its low end. Then shift the input right.
Repeat exactly 32 times so leading zeros are processed too. The first bit read is bit 0. By the end it has been shifted left 31 times, which puts it at position 31.
Steps
- Convert
nto an unsigned 32-bit value so right shifts bring in zeros. - Set
result = 0. - Repeat 32 times: set
result = (result << 1) | (n & 1). - After each round, shift
nright by one. - After the loop, if bit 31 of
resultis set, read it as signed (subtract 2^32 in Python). - Return
result.
Dry run
Input n = -2147483648, unsigned pattern 0x80000000, so only bit 31 is set.
- Rounds 1 to 31 read bits 0 through 30. Every one is 0, so
resultstays 0 after each shift and OR. - Round 32 reads bit 31, which is 1.
result = (0 << 1) | 1 = 1. - The loop ends. Bit 31 of
resultis clear, so the answer is 1.
Complexity
| Time | O(1) |
|---|---|
| Space | O(1) |
The loop runs exactly 32 times, and each round does a fixed number of shifts, ANDs, and ORs. That is 32 constant-time rounds, so the time is O(1) with a constant of about 32 rounds. Only the input and the result are stored, so space is O(1).
PythonTested in our runner
from typing import List, Optional
class Solution:
def reverseBits(self, n: int) -> int:
n &= 0xFFFFFFFF # keep only the 32-bit pattern
result = 0
for _ in range(32):
result = (result << 1) | (n & 1)
n >>= 1
# read the pattern as signed
if result >= 1 << 31:
result -= 1 << 32
return resultJavaTested in our runner
import java.util.*;
class Solution {
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
result = (result << 1) | (n & 1);
n >>>= 1; // logical shift, no sign extension
}
return result; // int already reads bit 31 as the sign
}
}C++Tested in our runner
class Solution {
public:
int reverseBits(int n) {
unsigned int u = static_cast<unsigned int>(n);
unsigned int result = 0;
for (int i = 0; i < 32; ++i) {
result = (result << 1) | (u & 1u);
u >>= 1;
}
return static_cast<int>(result);
}
};JavaScriptTested in our runner
/**
* @param {number} n
* @return {number}
*/
var reverseBits = function(n) {
let result = 0;
for (let i = 0; i < 32; i++) {
result = (result << 1) | (n & 1); // bitwise ops work on signed 32-bit
n >>>= 1; // logical shift
}
return result;
};GoTested in our runner
func reverseBits(n int) int {
u := uint32(n)
var result uint32
for i := 0; i < 32; i++ {
result = result<<1 | u&1
u >>= 1
}
return int(int32(result))
}C#Tested in our runner
public class Solution {
public int reverseBits(int n) {
uint u = unchecked((uint)n);
uint result = 0;
for (int i = 0; i < 32; i++) {
result = (result << 1) | (u & 1u);
u >>= 1;
}
return unchecked((int)result);
}
}
Solution pattern
Bitwise AND - Counting Set Bits (Hamming Weight)
Part of Bit Manipulation Patterns
Approach 3: Mask and swap in 5 stepsOptimalBitwise AND - Counting Set Bits (Hamming Weight)
What's slow: the loop touches one bit per round, so it needs 32 rounds. Each round does work that could be done for many bits at once.
The insight that fixes it: reversal is a divide and conquer. Reversing 32 bits equals swapping the two 16-bit halves, then reversing each half. Reversing a half equals swapping its two bytes and reversing each byte, and so on.
Each level swaps neighbouring blocks of one size across the whole word with one mask pair. The block sizes are 16, 8, 4, 2, 1, so five steps finish the job.
Steps
- Convert
nto an unsigned 32-bit value. - Swap the 16-bit halves:
n = (n >> 16) | (n << 16). - Swap adjacent bytes:
n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8). - Swap adjacent nibbles with masks
0xF0F0F0F0and0x0F0F0F0F, shifting by 4. - Swap adjacent bit pairs with masks
0xCCCCCCCCand0x33333333, shifting by 2. - Swap adjacent bits with masks
0xAAAAAAAAand0x55555555, shifting by 1. - Read the result as signed and return it.
Dry run
Input n = -2147483648, unsigned pattern 0x80000000. Track the single set bit.
| Step | Operation | Value (hex) | Set bit position |
|---|---|---|---|
| 0 | start | 0x80000000 | 31 |
| 1 | swap 16-bit halves | 0x00008000 | 15 |
| 2 | swap bytes: (0x8000 & 0xFF00) >> 8 = 0x80 | 0x00000080 | 7 |
| 3 | swap nibbles: (0x80 & 0xF0) >> 4 = 0x08 | 0x00000008 | 3 |
| 4 | swap pairs: (0x08 & 0xC) >> 2 = 0x02 | 0x00000002 | 1 |
| 5 | swap bits: (0x02 & 0xA) >> 1 = 0x01 | 0x00000001 | 0 |
| 6 | read as signed | 1 | bit 31 clear, so 1 |
The set bit moved from position 31 to position 0, and the answer is 1. In each step the other mask term, such as (n & 0x00FF00FF) << 8, was 0 because nothing sat in those positions.
Complexity
| Time | O(1) |
|---|---|
| Space | O(1) |
There are exactly five swap steps, and each is a fixed number of shifts, ANDs, and ORs on one word. The work does not depend on the value of n. Only one word of state is kept, so space is O(1). This is about 6 times fewer rounds than the 32-iteration loop.
PythonTested in our runner
from typing import List, Optional
class Solution:
def reverseBits(self, n: int) -> int:
n &= 0xFFFFFFFF
n = ((n >> 16) | (n << 16)) & 0xFFFFFFFF
n = (((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8)) & 0xFFFFFFFF
n = (((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4)) & 0xFFFFFFFF
n = (((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2)) & 0xFFFFFFFF
n = (((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1)) & 0xFFFFFFFF
# read the pattern as signed
if n >= 1 << 31:
n -= 1 << 32
return nJavaTested in our runner
import java.util.*;
class Solution {
public int reverseBits(int n) {
n = (n >>> 16) | (n << 16);
n = ((n & 0xFF00FF00) >>> 8) | ((n & 0x00FF00FF) << 8);
n = ((n & 0xF0F0F0F0) >>> 4) | ((n & 0x0F0F0F0F) << 4);
n = ((n & 0xCCCCCCCC) >>> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xAAAAAAAA) >>> 1) | ((n & 0x55555555) << 1);
return n;
}
}C++Tested in our runner
class Solution {
public:
int reverseBits(int n) {
unsigned int u = static_cast<unsigned int>(n);
u = (u >> 16) | (u << 16);
u = ((u & 0xFF00FF00u) >> 8) | ((u & 0x00FF00FFu) << 8);
u = ((u & 0xF0F0F0F0u) >> 4) | ((u & 0x0F0F0F0Fu) << 4);
u = ((u & 0xCCCCCCCCu) >> 2) | ((u & 0x33333333u) << 2);
u = ((u & 0xAAAAAAAAu) >> 1) | ((u & 0x55555555u) << 1);
return static_cast<int>(u);
}
};JavaScriptTested in our runner
/**
* @param {number} n
* @return {number}
*/
var reverseBits = function(n) {
// bitwise operators work on signed 32-bit ints; >>> is the logical shift
n = (n >>> 16) | (n << 16);
n = ((n & 0xFF00FF00) >>> 8) | ((n & 0x00FF00FF) << 8);
n = ((n & 0xF0F0F0F0) >>> 4) | ((n & 0x0F0F0F0F) << 4);
n = ((n & 0xCCCCCCCC) >>> 2) | ((n & 0x33333333) << 2);
n = ((n & 0xAAAAAAAA) >>> 1) | ((n & 0x55555555) << 1);
return n | 0;
};GoTested in our runner
func reverseBits(n int) int {
u := uint32(n)
u = u>>16 | u<<16
u = (u&0xFF00FF00)>>8 | (u&0x00FF00FF)<<8
u = (u&0xF0F0F0F0)>>4 | (u&0x0F0F0F0F)<<4
u = (u&0xCCCCCCCC)>>2 | (u&0x33333333)<<2
u = (u&0xAAAAAAAA)>>1 | (u&0x55555555)<<1
return int(int32(u))
}C#Tested in our runner
public class Solution {
public int reverseBits(int n) {
uint u = unchecked((uint)n);
u = (u >> 16) | (u << 16);
u = ((u & 0xFF00FF00u) >> 8) | ((u & 0x00FF00FFu) << 8);
u = ((u & 0xF0F0F0F0u) >> 4) | ((u & 0x0F0F0F0Fu) << 4);
u = ((u & 0xCCCCCCCCu) >> 2) | ((u & 0x33333333u) << 2);
u = ((u & 0xAAAAAAAAu) >> 1) | ((u & 0x55555555u) << 1);
return unchecked((int)u);
}
}Common mistakes
- Using
bin(n)orInteger.toBinaryString(n)without padding. Leading zeros vanish, so every position shifts. Pad to 32 characters, for exampleformat(n & 0xFFFFFFFF, '032b')in Python. - Looping
while n:instead offor _ in range(32). An input like 1 has 31 leading zeros that must be pushed through the result. Always run exactly 32 rounds. - Using
n >>= 1on a negative Java or JavaScript value. The arithmetic shift copies the sign bit, so the loop reads ones forever from the top. Usen >>>= 1, or an unsigned type in C++, Go and C#. - Skipping
n &= 0xFFFFFFFFin Python. A negative Python integer has infinite sign extension, son >> 1never reaches 0 and the bits you read are wrong. Mask first. - Returning the unsigned result in Python or JavaScript. For Example 1 you would return 2147483648 instead of -2147483648. Subtract 2^32 in Python when bit 31 is set, and use
| 0in JavaScript. - Writing
result = (result << 1) | n & 1and trusting precedence. In most C-like languages&binds tighter than|, so it works, but it hides intent. Put parentheses around(n & 1)so the bit read is obvious.
Edge cases
- n = 0 returns 0, since every bit is zero in both directions.
- n = -1 (all 32 bits set) returns -1, because reversing a pattern of all ones changes nothing.
- n = 1 returns -2147483648, and n = -2147483648 returns 1. The two are each other's reversal.
- n = -2 returns 2147483647, the example where the sign bit goes from set to clear.
- n = 2147483647 (0x7FFFFFFF) returns -2, because the 31 low ones move to bits 1 through 31 and bit 0 becomes 0.
- A palindromic pattern such as 0x80000001 (that is -2147483647) returns itself.
Follow-ups interviewers ask
- The function is called many times. How do you make it faster?
- Cache the reversal of each byte in a 256-entry table. Then reverse a 32-bit value by looking up its four bytes and placing them in the opposite order: byte 0 reversed goes to the top, byte 3 reversed goes to the bottom. That is four lookups, a few shifts, and no loop. A 65536-entry table for 16-bit halves works the same way with two lookups, at the cost of more memory.
- What if the input were 64 bits instead of 32?
- The shift loop runs 64 rounds. The mask version adds one more level, swapping 32-bit halves first, then using 64-bit versions of the same masks. The idea and the O(1) cost per call do not change. Every constant and every type must widen to 64 bits.
- Can you do it without a loop or a lookup table?
- Yes, the five masked swaps do that. Each step swaps neighbouring blocks of size 16, 8, 4, 2, then 1. A bit at position p lands at 31 - p, which is p with all five index bits flipped, and each step flips exactly one index bit. There is no loop and no extra memory.
Reverse Bits FAQ
What is the time complexity of Reverse Bits?
It is O(1), because the word is always 32 bits. The shift loop does 32 rounds of constant work, and the mask-and-swap version does 5 steps. Space is O(1) as well. If the width were w bits, the loop would cost O(w) and the swap version O(log w).
Why use bit manipulation for Reverse Bits?
The problem is defined by bit positions, not by numeric value. Reading a bit with n & 1 and moving bits with shifts lets you place each bit directly at position 31 - p. Strings force you to handle padding and sign yourself, and they allocate memory for no gain.
How do you solve LeetCode 190 in Python?
Mask the input with n &= 0xFFFFFFFF. Run a loop 32 times doing result = (result << 1) | (n & 1) and n >>= 1. Then subtract 1 << 32 if result is at least 1 << 31. The mask and the final subtraction are needed because Python integers are unbounded.
How do you solve Reverse Bits in Java?
Java int is already 32-bit two's complement. Loop 32 times with result = (result << 1) | (n & 1) and use n >>>= 1 so no sign bits are copied in. Return result directly, because an int with bit 31 set is already negative. Integer.reverse(n) does the same thing in the standard library.
Why does Reverse Bits return a negative number for n = 1?
Reversal moves the lowest bit to position 31. In signed 32-bit two's complement, position 31 is the sign bit and is worth -2^31. A pattern with only that bit set is -2147483648.
Can Reverse Bits be solved in O(1) extra space?
Yes. The shift loop uses two integers, and the mask-and-swap version uses one. Even the string version uses only a fixed 32 characters, so every approach here is O(1) space.
Asked at
See which companies ask this — Pro
Related problems
- Number of 1 Bits · same technique: Bitwise AND - Counting Set Bits (Hamming Weight)
- Power of Two · same technique: Bitwise AND - Counting Set Bits (Hamming Weight)
- Pow(x, n) · next harder, same pattern
- Single Number · same pattern: Bit Manipulation Patterns
- Missing Number · same pattern: Bit Manipulation Patterns
- Counting Bits · same pattern: Bit Manipulation Patterns
- Find the Difference · same pattern: Bit Manipulation Patterns
- Power of Four · same pattern: Bit Manipulation Patterns
- Sum of Two Integers · same pattern: Bit Manipulation Patterns
- Bitwise AND of Numbers Range · same pattern: Bit Manipulation Patterns