题目原文:
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.
Example:
For num = 5 you should return [0,1,1,2,1,2].
题目大意:
输入一个正整数num,返回一个num+1长的数组,代表从0~num每个数二进制码中1的个数。
题目分析:
用Java中的Integer.bitCount这个函数水过去。
源码:(language:java)
public class Solution {
public int[] countBits(int num) {
int[] bits = new int[num+1];
for(int i = 0;i<=num;i++)
bits[i] = Integer.bitCount(i);
return bits;
}
}
成绩:
5ms(统计信息还未显示)
Cmershen的碎碎念:
附JDK中bitCount的算法(大概是一个很巧妙的”分治算法”的位运算,复杂度O(1))
public static int bitCount(int i) {
// HD, Figure 5-2
i = i - ((i >>> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);
i = (i + (i >>> 4)) & 0x0f0f0f0f;
i = i + (i >>> 8);
i = i + (i >>> 16);
return i & 0x3f;
}
有时间把那些二进制位写开认真分析一下。