版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
/*题目 *输入一个整数,输出该数二进制表示中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;
}