博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
返回0~n的二进制表示中1的个数 Counting Bits
阅读量:7048 次
发布时间:2019-06-28

本文共 1773 字,大约阅读时间需要 5 分钟。

hot3.png

问题:

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.

解决:

【题意】给定n,然后计算从0到n之间所有的数的bit为1的个数。

【注】之前有的hint,后来被删了。

Hint:

  1. You should make use of what you have produced already.
  2. Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
  3. Or does the odd/even status of the number help you in calculating the number of 1s?

①  直接解决。时间复杂度O(n*sizeof(integer))。

class Solution {//4ms

    public int[] countBits(int num) {
        int[] res = new int[num + 1];
        for (int i = 0;i <= num;i ++){
            if (i == 0){
                res[i] = 0;
            }else{
                int count = 1;
                int tmp = i;
                while((tmp & (tmp - 1)) != 0){
                    count ++;
                    tmp = (tmp & (tmp - 1));
                }
                res[i] = count;
            }
        }
        return res;
    }
}

② 对于数字2(10), 4(100), 8(1000), 16(10000), ...,其二进制表示中只有1个1。其他任意数字都可以表示为2^m + x。例如9=8+1, 10=8+2。其他任意数字中1的个数是1 + x中1的个数。时间复杂度O(n)

Counting Bits (Java)

class Solution { //3ms

    public int[] countBits(int num) {
        int[] res = new int[num + 1];
        int p = 1;//p指向x的下标
        int pow = 1;//指向2的幂
        for (int i = 1;i <= num;i ++){
            if (i == pow){
                res[i] = 1;
                pow <<= 1;
                p = 1;
            }else{
                res[i] = res[p] + 1;
                p ++;
            }
        }
        return res;
    }
}

③ 

 class Solution {//2ms

    public int[] countBits(int num) {
        int[] res = new int[num + 1];
        for (int i = 1;i <= num;i ++){
            res[i] = res[i & (i - 1)] + 1;
        }
        return res;
    }
}

转载于:https://my.oschina.net/liyurong/blog/1594940

你可能感兴趣的文章
java中堆(heap)和堆栈(stack)
查看>>
H3C 5500/5820 端口聚合LACP
查看>>
手动在linux中源码编译安装httpd
查看>>
JDK和Android SDK环境变量配置
查看>>
如何实现导航菜单栏中的二级下拉菜单?
查看>>
我的友情链接
查看>>
ssh典型面试题
查看>>
最大子序列相关问题
查看>>
Forefront TMG 服务器中如何规划和实现高可用性
查看>>
Exchange Server 2010 故障分享
查看>>
java正则匹配count字符串
查看>>
Exchange2007/2010如何恢复被禁用或者删除的邮箱
查看>>
第五天:Before -- CMD
查看>>
Docker软件安装系列。
查看>>
我的友情链接
查看>>
LEFT JOIN连表时,ON后多条件无效问题
查看>>
[20180423]flashback tablespace与snapshot standby.txt
查看>>
php中禁止单个ip与ip段访问的代码小结
查看>>
LeetCode-330.Patching Array
查看>>
zxing生成二维码转base64 img直接显示 Image对象转Base64码(java)
查看>>