一、题目描述
给你一个整数 n ,对于 0 <= i <= n 中的每个 i ,计算其二进制表示中 1 的个数 ,返回一个长度为 n + 1 的数组 ans 作为答案。
示例一
输入:n = 2 输出:[0,1,1] 解释: 0 --> 0 1 --> 1 2 --> 10
二、解题思路
1)暴力算法:循环1~n,再利用循环计算每个数中包含的1的个数
public int[] countBits(int n) {
int[] nums = new int[n + 1];
for (int i = 1; i < n; i++) {
nums[i] = count(i);
}
return nums;
}
public int count(int n) {
int sum = 0;
//每次与上一次都会消去一个1
while (n > 0) {
n = n & (n - 1);
sum++;
}
return sum;
}
2)利用动态规划。
public int[] countBits02(int n) {
int[] bits = new int[n + 1];
bits[0] = 0;
int hightBits = 0;
for (int i = 1; i <= n; i++) {
if ((i & (i - 1)) == 0) {
hightBits = i;
}
bits[i] = bits[i - hightBits] + 1;
}
return bits;
}
本文探讨了一种使用动态规划解决给定整数n的二进制表示中1的个数计算问题的解法。通过构造bits数组并利用hightBits变量,避免了重复计算,提供了一种简洁且性能优越的算法。
188

被折叠的 条评论
为什么被折叠?



