LeetCode 题解工作台

颠倒二进制位

颠倒给定的 32 位有符号整数的二进制位。 示例 1: 输入: n = 43261596 输出: 964176192 解释: 整数 二进制 43261596 00000010100101000001111010011100 964176192 0011100101111000001010010100…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · divide·conquer·结合·位运算·操作

bolt

答案摘要

我们可以从低位到高位,逐个取出 的每一位,然后将其放到 的对应位置上。 比如,对于第 位,我们可以通过 $(n \& 1) \ll (31 - i)$ 来取出 的第 位,并将其放到 的第 $31 - i$ 位上,然后将 右移一位。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 divide·conquer·结合·位运算·操作 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

颠倒给定的 32 位有符号整数的二进制位。

 

示例 1:

输入:n = 43261596

输出:964176192

解释:

整数 二进制
43261596 00000010100101000001111010011100
964176192 00111001011110000010100101000000

示例 2:

输入:n = 2147483644

输出:1073741822

解释:

整数 二进制
2147483644 01111111111111111111111111111100
1073741822 00111111111111111111111111111110

 

提示:

  • 0 <= n <= 231 - 2
  • n 为偶数

 

进阶: 如果多次调用这个函数,你将如何优化你的算法?

lightbulb

解题思路

方法一:位运算

我们可以从低位到高位,逐个取出 nn 的每一位,然后将其放到 ans\textit{ans} 的对应位置上。

比如,对于第 ii 位,我们可以通过 (n&1)(31i)(n \& 1) \ll (31 - i) 来取出 nn 的第 ii 位,并将其放到 ans\textit{ans} 的第 31i31 - i 位上,然后将 nn 右移一位。

时间复杂度 O(logn)O(\log n),空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
class Solution:
    def reverseBits(self, n: int) -> int:
        ans = 0
        for i in range(32):
            ans |= (n & 1) << (31 - i)
            n >>= 1
        return ans
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

颠倒二进制位题解:divide·conquer·结合·位运算·操作 | LeetCode #190 简单