LeetCode 题解工作台
使两个整数相等的位更改次数
给你两个正整数 n 和 k 。 你可以选择 n 的 二进制表示 中任意一个值为 1 的位,并将其改为 0。 返回使得 n 等于 k 所需要的更改次数。如果无法实现,返回 -1。 示例 1: 输入: n = 13, k = 4 输出: 2 解释: 最初, n 和 k 的二进制表示分别为 n = (11…
1
题型
7
代码语言
3
相关题
当前训练重点
简单 · 位运算·操作·driven·solution·strategy
答案摘要
如果 和 的按位与结果不等于 ,说明 存在某一位为 ,而 对应的位为 ,此时无法通过改变 的某一位使得 等于 ,返回 ;否则,我们统计 $n \oplus k$ 的二进制表示中 的个数即可。 时间复杂度 $O(\log n)$,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 位运算·操作·driven·solution·strategy 题型思路
题目描述
给你两个正整数 n 和 k。
你可以选择 n 的 二进制表示 中任意一个值为 1 的位,并将其改为 0。
返回使得 n 等于 k 所需要的更改次数。如果无法实现,返回 -1。
示例 1:
输入: n = 13, k = 4
输出: 2
解释:
最初,n 和 k 的二进制表示分别为 n = (1101)2 和 k = (0100)2,
我们可以改变 n 的第一位和第四位。结果整数为 n = (0100)2 = k。
示例 2:
输入: n = 21, k = 21
输出: 0
解释:
n 和 k 已经相等,因此不需要更改。
示例 3:
输入: n = 14, k = 13
输出: -1
解释:
无法使 n 等于 k。
提示:
1 <= n, k <= 106
解题思路
方法一:位运算
如果 和 的按位与结果不等于 ,说明 存在某一位为 ,而 对应的位为 ,此时无法通过改变 的某一位使得 等于 ,返回 ;否则,我们统计 的二进制表示中 的个数即可。
时间复杂度 ,空间复杂度 。
class Solution:
def minChanges(self, n: int, k: int) -> int:
return -1 if n & k != k else (n ^ k).bit_count()
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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.