剑指Offer-11-二进制1的数

题目描述

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

public class Solution {
    public int NumberOf1(int n) {
        int count = 0;
        while(n!=0){
            count++;
            n = n & (n-1);
        }   
        return count;
    }
}
public class Solution {
    public int NumberOf1(int n) {
        /*int count = 0;
        while(n!=0){
            count++;
            n = n & (n-1);
        }   
        return count;*/
        int count = 0;
        for(int i=1;i<=32;i++){
            if((n&1)==1){
                count++;
            }
            n = n >> 1;
        }
        return count;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_27378875/article/details/81159095