LeetCode 题解工作台

使两个整数相等的位更改次数

给你两个正整数 n 和 k 。 你可以选择 n 的 二进制表示 中任意一个值为 1 的位,并将其改为 0。 返回使得 n 等于 k 所需要的更改次数。如果无法实现,返回 -1。 示例 1: 输入: n = 13, k = 4 输出: 2 解释: 最初, n 和 k 的二进制表示分别为 n = (11…

category

1

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

简单 · 位运算·操作·driven·solution·strategy

bolt

答案摘要

如果 和 的按位与结果不等于 ,说明 存在某一位为 ,而 对应的位为 ,此时无法通过改变 的某一位使得 等于 ,返回 ;否则,我们统计 $n \oplus k$ 的二进制表示中 的个数即可。 时间复杂度 $O(\log n)$,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 位运算·操作·driven·solution·strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个正整数 nk

你可以选择 n二进制表示 中任意一个值为 1 的位,并将其改为 0。

返回使得 n 等于 k 所需要的更改次数。如果无法实现,返回 -1。

 

示例 1:

输入: n = 13, k = 4

输出: 2

解释:
最初,nk 的二进制表示分别为 n = (1101)2k = (0100)2

我们可以改变 n 的第一位和第四位。结果整数为 n = (0100)2 = k

示例 2:

输入: n = 21, k = 21

输出: 0

解释:
nk 已经相等,因此不需要更改。

示例 3:

输入: n = 14, k = 13

输出: -1

解释:
无法使 n 等于 k

 

提示:

  • 1 <= n, k <= 106
lightbulb

解题思路

方法一:位运算

如果 nnkk 的按位与结果不等于 kk,说明 kk 存在某一位为 11,而 nn 对应的位为 00,此时无法通过改变 nn 的某一位使得 nn 等于 kk,返回 1-1;否则,我们统计 nkn \oplus k 的二进制表示中 11 的个数即可。

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

1
2
3
4
class Solution:
    def minChanges(self, n: int, k: int) -> int:
        return -1 if n & k != k else (n ^ k).bit_count()
speed

复杂度分析

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

面试官常问的追问

外企场景
  • question_mark

    Look for candidates who understand bit manipulation concepts like XOR and bit shifts.

  • question_mark

    Evaluate how well the candidate can translate bitwise operations into a solution strategy.

  • question_mark

    Assess the candidate’s understanding of edge cases, like impossibilities in the transformation of n to k.

warning

常见陷阱

外企场景
  • error

    Forgetting that bits in k set to 1 when corresponding bits in n are 0 make the problem unsolvable.

  • error

    Incorrectly assuming that the binary representation comparison only requires a one-to-one match, overlooking the transformation rules.

  • error

    Misunderstanding the XOR operation and not using it to efficiently detect bit differences.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Extend this problem to include multiple integers and find the minimum number of changes to make all integers equal.

  • arrow_right_alt

    Consider a variant where bits can be flipped both ways (0 to 1 and 1 to 0) to make n equal to k.

  • arrow_right_alt

    Introduce a time limit constraint for large inputs and test the efficiency of the solution.

help

常见问题

外企场景

使两个整数相等的位更改次数题解:位运算·操作·driven·solution·… | LeetCode #3226 简单