正整数的二进制表示中1的个数计算(使用移位或者n&(n-1))

第一种:使用n&(n-1)表示来计算有多少个1

            int n=127;
            int count=0;
            while (n!=0){
                count++;
                n=n&(n-1);
            }

第二种:使用移位操作

           Integer input = in.nextInt();
           int count=0;
           for(int i=0;i<30;i++){
               int tmp = (input >> i)&0x00000001;
               if(tmp==1){
                   count++;
               }
           }

            System.out.println(count);
原文地址:https://www.cnblogs.com/InternetJava/p/12543186.html