zoukankan      html  css  js  c++  java
  • [leetcode] Number of 1 Bits

    1.先上题:

    Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

    For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

    2.一眼看到这个题感觉好简单,AC率才30%+,心里沾沾自喜。。 岂料,提交之后竟然WA了!!!!  测试用例中有个数据是2147483648,这是超出了JAVA int型范围的,不明白测试数据为什么会有这个?  这到底是why? (现在觉得可能就是下面这个无符号的问题 ,假如存在无符号,范围应该是0~2^32-1 )

        百度之后才知道原来 JAVA没有无符号类型 ,然后题的代码提示说 要把n 当做无符号数处理,所以只能位运算了!

    3. 在JAVA中对于一个整型变量,其默认类型是int型,范围是-2^31~2^31-1 (-2147483648~2147483647) .

     AC代码:

    public int hammingWeight(int n){

    int record=0;
    while(n!=0) {
    record++;
    n&=n-1;
    }
    //System.out.println(record);
    return record;
    }

    在网上查一下都是推荐这种算法,但是不知道AC之后看到有很多100ms之内的算法,不知道大牛们是怎么实现的! 

  • 相关阅读:
    centos7 源码安装python3
    gitlab 迁移
    gitlab 搭建
    亚伦史沃茨 公开信
    误删了sudo包怎么办
    在中国历史上,我个人最喜欢的三个皇帝
    安装PHP7
    Mac OS上设置Django开发环境
    The Pragmatic Programmer Quick Reference Guide
    Nginx的第一个模块-HelloWorld
  • 原文地址:https://www.cnblogs.com/summer323/p/4482724.html
Copyright © 2011-2022 走看看