LeetCode 题解工作台
颠倒二进制位
颠倒给定的 32 位有符号整数的二进制位。 示例 1: 输入: n = 43261596 输出: 964176192 解释: 整数 二进制 43261596 00000010100101000001111010011100 964176192 0011100101111000001010010100…
2
题型
7
代码语言
3
相关题
当前训练重点
简单 · divide·conquer·结合·位运算·操作
答案摘要
我们可以从低位到高位,逐个取出 的每一位,然后将其放到 的对应位置上。 比如,对于第 位,我们可以通过 $(n \& 1) \ll (31 - i)$ 来取出 的第 位,并将其放到 的第 $31 - i$ 位上,然后将 右移一位。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 divide·conquer·结合·位运算·操作 题型思路
题目描述
颠倒给定的 32 位有符号整数的二进制位。
示例 1:
输入:n = 43261596
输出:964176192
解释:
| 整数 | 二进制 |
|---|---|
| 43261596 | 00000010100101000001111010011100 |
| 964176192 | 00111001011110000010100101000000 |
示例 2:
输入:n = 2147483644
输出:1073741822
解释:
| 整数 | 二进制 |
|---|---|
| 2147483644 | 01111111111111111111111111111100 |
| 1073741822 | 00111111111111111111111111111110 |
提示:
0 <= n <= 231 - 2n为偶数
进阶: 如果多次调用这个函数,你将如何优化你的算法?
解题思路
方法一:位运算
我们可以从低位到高位,逐个取出 的每一位,然后将其放到 的对应位置上。
比如,对于第 位,我们可以通过 来取出 的第 位,并将其放到 的第 位上,然后将 右移一位。
时间复杂度 ,空间复杂度 。
class Solution:
def reverseBits(self, n: int) -> int:
ans = 0
for i in range(32):
ans |= (n & 1) << (31 - i)
n >>= 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity depends on the chosen approach: iterative and recursive divide-and-conquer methods run in O(1) since the bit length is fixed at 32, while the lookup table method also achieves O(1) with faster constant-time operations. Space complexity varies: iterative uses O(1), recursive uses O(log32)=O(1) stack, and lookup table uses O(256) for precomputation. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Expect candidates to recognize bit-level patterns and swap sequences.
- question_mark
Look for proper handling of masks and shifts without off-by-one errors.
- question_mark
Assess whether the candidate applies divide and conquer to sub-bit blocks correctly.
常见陷阱
外企场景- error
Incorrectly swapping bits without using proper masks leading to wrong output.
- error
Forgetting to handle all 32 bits consistently in iterative or recursive steps.
- error
Misaligning left and right halves when merging, producing off-by-one bit errors.
进阶变体
外企场景- arrow_right_alt
Reverse bits for integers of arbitrary bit lengths, not limited to 32 bits.
- arrow_right_alt
Count the number of 1s after reversing bits to combine bit manipulation patterns.
- arrow_right_alt
Perform in-place bit reversal for arrays of integers using the same divide and conquer principle.