338. Counting Bits

来源:互联网 发布:网络液晶广告机 编辑:程序博客网 时间:2024/06/01 22:19

1.题目
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.

2.分析
  这道题很明显就是一道动态规划的题目,每次计算当前的二进制1的个数时,需要使用保存的前一个数二进制数中1的个数的基础上进行计数。

3.解题
我的解法:

public class Solution {public int[] countBits(int num) {    int[]result = new int[num+1];    if(num==0){        return result;    }    for(int i=0;i<num;i++){        result[i] = i;    }    int count = 0;    while(num/2!=0){        count++;        num = num/2;    }    for(int i=1;i<result.length;i++){        if((i-1)%2==0){            result[i] = result[i-1]+1;        } else if((i-1)%2!=0){            String str = Integer.toBinaryString(i-1);            int countsum = 0;            for(int j=str.length()-1;j>=0;j--){                if(str.charAt(j)=='1'){                    countsum++;                }else{                    break;                }            }            result[i] = result[i-1]-countsum+1;        }    }    return result;}}}

4.总结
  我怎么感觉大家的方法都好简短,不是很好懂,而且一般找数值规律,总觉得像是投机取巧,当然能想到已经很厉害了,还是多看看优秀的人写得东西,才能成长- -。。

原创粉丝点击