十进制转成二进制中1的个数

解法一:让临时变量每次乘以二再与源数字相与,测试每一位上的数字是否为1

  public int NumberOf1(int n) {
         int temp=1,count=0;
     while(temp!=0){
         if((temp&n)!=0){
             count++;
         }
         temp=temp<<1;
     }
         return count;
     }

解法二:将原来的数字减一再与源数相与,为0则说明该位为0,不为0 则说明该为不为0数字中有多少个1 就循环多少次

public int NumberOf1(int n) {
int temp,count=0;
while(n!=0){
temp=n-1;
n=temp&n;
if(n!=0){
count++;
}
}
return count;

猜你喜欢

转载自blog.csdn.net/jh_ww/article/details/80551376