华为机试测试-整数中二进制1的个数

    public static  int isPowerOfTwo(int n) {
        int cnt=0;
        while(n!=0)
        {
            cnt++;
            n=n&(n-1);
        }
        return cnt;
    }

 本质上是从低位到高位求1的个数!

n&(n-1)可以去掉最低位的1.

posted @ 2015-09-08 15:32  Maydow  阅读(146)  评论(0编辑  收藏  举报