奇偶位数
难度:
标签:
题目描述
You are given a positive integer n
.
Let even
denote the number of even indices in the binary representation of n
(0-indexed) with value 1
.
Let odd
denote the number of odd indices in the binary representation of n
(0-indexed) with value 1
.
Return an integer array answer
where answer = [even, odd]
.
Example 1:
Input: n = 17 Output: [2,0] Explanation: The binary representation of 17 is 10001. It contains 1 on the 0th and 4th indices. There are 2 even and 0 odd indices.
Example 2:
Input: n = 2 Output: [0,1] Explanation: The binary representation of 2 is 10. It contains 1 on the 1st index. There are 0 even and 1 odd indices.
Constraints:
1 <= n <= 1000
代码结果
运行时间: 20 ms, 内存: 16.1 MB
/*
* 思路:
* 1. 将正整数 n 转换为二进制字符串。
* 2. 使用 Java Stream 处理字符串并统计偶数下标和奇数下标的 '1' 的个数。
* 3. 将统计结果以数组形式返回。
*/
import java.util.stream.IntStream;
public class Solution {
public int[] evenOddCount(int n) {
String binaryString = Integer.toBinaryString(n);
int even = (int) IntStream.range(0, binaryString.length())
.filter(i -> i % 2 == 0 && binaryString.charAt(i) == '1')
.count();
int odd = (int) IntStream.range(0, binaryString.length())
.filter(i -> i % 2 != 0 && binaryString.charAt(i) == '1')
.count();
return new int[]{even, odd};
}
}
解释
方法:
该题解通过遍历整数 n 的二进制位来统计奇数位和偶数位上值为 1 的位的数量。使用一个循环,每次迭代检查 n 的最低位(n & 1),根据当前位的下标是奇数还是偶数(通过计数器 cnt 实现),更新奇数位或偶数位的计数器。每次迭代后,n 右移一位(n >>= 1),即去掉已经检查过的最低位,同时计数器 cnt 自增1,直到 n 为 0。
时间复杂度:
O(log n)
空间复杂度:
O(1)
代码细节讲解
🦆
在实现过程中,为什么选择使用位运算(n & 1)来检查最低位的值?
▷🦆
题解中提到每次迭代后将 n 右移一位(n >>= 1),这种操作是否可能导致某些情况下遗漏检查某些位的值?
▷🦆
变量 cnt 的初始值为0,这样设置的原因是什么?对于二进制位的计数来说,从0开始和从1开始有何区别?
▷🦆
在题解的代码中没有特别处理 n=0 的情况,这样处理是否适当?
▷