LeetCode 题解工作台
奇偶位数
给你一个 正 整数 n 。 用 even 表示在 n 的二进制形式(下标从 0 开始)中值为 1 的偶数下标的个数。 用 odd 表示在 n 的二进制形式(下标从 0 开始)中值为 1 的奇数下标的个数。 请注意,在数字的二进制表示中,位下标的顺序 从右到左 。 返回整数数组 answer ,其中 …
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · 位运算·操作·driven·solution·strategy
答案摘要
我们根据题意,枚举 的二进制表示中从低位到高位的每一位,如果该位为 ,则根据该位的下标是奇数还是偶数,将对应的计数器加 即可。 时间复杂度 $O(\log n)$,空间复杂度 。其中 为给定的整数。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 位运算·操作·driven·solution·strategy 题型思路
题目描述
给你一个 正 整数 n 。
用 even 表示在 n 的二进制形式(下标从 0 开始)中值为 1 的偶数下标的个数。
用 odd 表示在 n 的二进制形式(下标从 0 开始)中值为 1 的奇数下标的个数。
请注意,在数字的二进制表示中,位下标的顺序 从右到左。
返回整数数组 answer ,其中 answer = [even, odd] 。
示例 1:
输入:n = 50
输出:[1,2]
解释:
50 的二进制表示是 110010。
在下标 1,4,5 对应的值为 1。
示例 2:
输入:n = 2
输出:[0,1]
解释:
2 的二进制表示是 10。
只有下标 1 对应的值为 1。
提示:
1 <= n <= 1000
解题思路
方法一:枚举
我们根据题意,枚举 的二进制表示中从低位到高位的每一位,如果该位为 ,则根据该位的下标是奇数还是偶数,将对应的计数器加 即可。
时间复杂度 ,空间复杂度 。其中 为给定的整数。
class Solution:
def evenOddBit(self, n: int) -> List[int]:
ans = [0, 0]
i = 0
while n:
ans[i] += n & 1
i ^= 1
n >>= 1
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for an understanding of bit manipulation techniques.
- question_mark
Expect the candidate to optimize the solution with efficient operations like bit shifting.
- question_mark
Pay attention to the candidate’s ability to maintain multiple counters for specific conditions.
常见陷阱
外企场景- error
Candidates may attempt a less efficient solution using string conversion or array manipulation.
- error
Confusing even and odd indices, leading to incorrect counting.
- error
Overcomplicating the solution with unnecessary loops or data structures.
进阶变体
外企场景- arrow_right_alt
Count bits at even and odd indices for larger integers.
- arrow_right_alt
Consider extending the problem to work with negative integers, adjusting for the sign bit.
- arrow_right_alt
Handle cases where the binary representation has fewer bits than the typical word length.