华为机试测试-整数中二进制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.

原文地址:https://www.cnblogs.com/maydow/p/4791891.html