输入一个整数 n ,输出该数32位二进制表示中1的个数。其中负数用补码表示。
数据范围:
即范围为:
10
2
十进制中10的32位二进制表示为0000 0000 0000 0000 0000 0000 0000 1010,其中有两个1。
-1
32
负数使用补码表示 ,-1的32位二进制表示为1111 1111 1111 1111 1111 1111 1111 1111,其中32个1
public class Solution { public int NumberOf1(int n) { int ans=0; while(n!=0){ ans+=n&1;//判断n的最右位是不是1 n>>>=1; //把n向右移动一位 } return ans; } }
public static int NumberOf1(int n) { int count = 0; for (int i = 0; i < 32; i++) { if( (n & 1) == 1){ count++; } n = n>>1; } return count; }
public int NumberOf1(int n) { int a = 0; while (n != 0) { if ((n & 1) == 1) { a++; } n = n>>>1; } return a; }
public class Solution { public int NumberOf1(int n) { // 定义计数器 int count=0; // int类型是32位,所以循环32次 for(int i=0;i<32;i++){ // 每一次都要检查末位是否为1 if( (n&1)==1 ){ count++; } // 右移一位 n = n>>1; } return count; } }优化:
public class Solution { public int NumberOf1(int n) { // 定义计数器 int count=0; // int类型是32位,所以循环32次 while(n!=0){ // 每一次都要检查末位是否为1 if( (n&1)==1 ){ count++; } // 右移一位(使用无符号右移,补码最高位补0而不是1,所以最多循环32次) n = n>>>1; } return count; } }