Leetcode 338. Counting Bits

来源:互联网 发布:工行信用卡 知乎 编辑:程序博客网 时间:2024/04/26 17:54

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].

Follow up:

It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?Space complexity should be O(n).Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

思路:
注:题意中说明不能使用库函数
此题中是计算0~num 的每个数的二进制中包含的1的个数的计算,0的二进制中的1为0个,之后的计算,考虑两种情况:
1)该为是2的幂次方,则二进制只包含一个1
2)该位不是2的幂次方,则二进制的位数 = 比该位数字小,且最接近的2的幂次方的1的个数+(该位数值-比该位数字小,且最接近的2的幂次方的数)的数的1的个数

具体代码如下:

public class Solution {    public int[] countBits(int num) {        int[] result = new int[num+1];        result[0] = 0;        int flag = 0;//标记上一个2的次幂的位置        int pow =1;        for(int i = 1; i < num+1; i++){            if(i == pow){                pow *= 2;                result[i] = 1;                flag = i;            }            else{                result[i] = result[flag]+ result[i-flag];            }        }        return result;    }}
0 0
原创粉丝点击