顿搜
飞过闲红千叶,夕岸在哪
类目归类
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
For num = 5 you should return [0,1,1,2,1,2].
public int[] countBits(int num)
{
int[] res = new int[num + 1];
for (int i = 1; i <= num; i++) {
res[i] = res[i >> 1] + (i & 1);
}
return res;
}public int[] countBits(int num)
{
int[] results = new int[num + 1];
for (int i = 0; i <= num; i++) {
results[i] = bitCount(i);
}
return results;
}
private int bitCount(int number)
{
int count = 0;
while (number != 0) {
count++;
number = (number - 1) & number;
}
return count;
}public class LeetCode0338 {
public int[] countBits(int num)
{
int[] res = new int[num + 1];
for (int i = 1; i <= num; i++) {
res[i] = res[i >> 1] + (i & 1);
}
return res;
}
public static void main(String[] args)
{
LeetCode0038 leetcode = new LeetCode0038();
int[] results = leetcode.countBits(5);
for (int result : results) {
System.out.println(result);
}
}
}public class LeetCode0338 {
public int[] countBits(int num)
{
int[] results = new int[num + 1];
for (int i = 0; i <= num; i++) {
results[i] = bitCount(i);
}
return results;
}
private int bitCount(int number)
{
int count = 0;
while (number != 0) {
count++;
number = (number - 1) & number;
}
return count;
}
public static void main(String[] args)
{
LeetCode0338 leetcode = new LeetCode0338();
int[] results = leetcode.countBits(5);
for (int result : results) {
System.out.println(result);
}
}
}