【Leetcode 每日一题】2595. 奇偶位数
问题背景
给你一个 正 整数
n
n
n。
用
e
v
e
n
even
even 表示在
n
n
n 的二进制形式(下标从
0
0
0 开始)中值为
1
1
1 的偶数下标的个数。
用
o
d
d
odd
odd 表示在
n
n
n 的二进制形式(下标从
0
0
0 开始)中值为
1
1
1 的奇数下标的个数。
请注意,在数字的二进制表示中,位下标的顺序 从右到左。
返回整数数组
a
n
s
w
e
r
answer
answer,其中
a
n
s
w
e
r
=
[
e
v
e
n
,
o
d
d
]
answer = [even, odd]
answer=[even,odd]。
数据约束
- 1 ≤ n ≤ 1000 1 \le n \le 1000 1≤n≤1000
解题过程
二进制相关的问题,基本都可以用移位遍历的思路来解决,但是通常也会有不需要循环的骚操作,权当长见识吧。
具体实现
移位遍历
class Solution {
public int[] evenOddBit(int n) {
int[] res = new int[2];
for (int i = 0; n > 0; n >>= 1) {
res[i] += n & 1;
// 0 和 1 之间可以通过异或 1 的操作相互转换
i ^= 1;
}
return res;
}
}
掩码位运算
class Solution {
// 5 的二进制表示是四位的 0 和 1 交替出现的
private static final int MASK = 0x55555555;
public int[] evenOddBit(int n) {
return new int[]{Integer.bitCount(n & MASK), Integer.bitCount(n & ~MASK)};
}
}