LeetCode 题解工作台

仅含置位位的最小整数

给你一个正整数 n 。 返回 大于等于 n 且二进制表示仅包含 置位 位的 最小 整数 x 。 置位 位指的是二进制表示中值为 1 的位。 示例 1: 输入: n = 5 输出: 7 解释: 7 的二进制表示是 "111" 。 示例 2: 输入: n = 10 输出: 15 解释: 15 的二进制表…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·位运算

bolt

答案摘要

我们从 $x = 1$ 开始,不断将 左移,直到 $x - 1 \geq n$,此时 $x - 1$ 就是我们要找的答案。 时间复杂度 $O(\log n)$,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·位运算 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个正整数 n

返回 大于等于 n 且二进制表示仅包含 置位 位的 最小 整数 x 。

置位 位指的是二进制表示中值为 1 的位。

 

示例 1:

输入: n = 5

输出: 7

解释:

7 的二进制表示是 "111"

示例 2:

输入: n = 10

输出: 15

解释:

15 的二进制表示是 "1111"

示例 3:

输入: n = 3

输出: 3

解释:

3 的二进制表示是 "11"

 

提示:

  • 1 <= n <= 1000
lightbulb

解题思路

方法一:位运算

我们从 x=1x = 1 开始,不断将 xx 左移,直到 x1nx - 1 \geq n,此时 x1x - 1 就是我们要找的答案。

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

1
2
3
4
5
6
7
class Solution:
    def smallestNumber(self, n: int) -> int:
        x = 1
        while x - 1 < n:
            x <<= 1
        return x - 1
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Candidate understands the concept of powers of two and bit manipulation.

  • question_mark

    Candidate applies bit manipulation to efficiently compute the answer.

  • question_mark

    Candidate avoids brute force approaches and seeks optimized solutions.

warning

常见陷阱

外企场景
  • error

    Misunderstanding the binary representation of numbers with all set bits.

  • error

    Using inefficient or brute force methods to calculate the result.

  • error

    Overcomplicating the problem and missing simple bitwise solutions.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if n is already a number with all set bits?

  • arrow_right_alt

    What if n is at the maximum limit (1000)?

  • arrow_right_alt

    What if n is a power of two, and no subtraction is needed?

help

常见问题

外企场景

仅含置位位的最小整数题解:数学·位运算 | LeetCode #3370 简单