二进制中1的个数——剑指offer(Java)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/dadajixxx/article/details/87940045
/*题目
 *输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。
 * */

/*思路
 *
 * (n-1) & n 操作会使 末尾变0
 * 5 =》 101    4 =》 100   101 & 100 = 100; 如果有1继续再来 知道a=0;
 *
 * 概念: 1 & 1 = 1      1 & 0 = 0
 * */
 public int NumberOf1(int n){

        int count = 0 ;

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

猜你喜欢

转载自blog.csdn.net/dadajixxx/article/details/87940045