劍指Offer-12-二進制中1的個數

/**
 * 二進制中1的個數
 * @Description
 */
public class Test13 {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count = 0;
        while (n != 0){
            count++;
            n = (n - 1) & n;
        }
        return count;
    }

    public int hammingWeight2(int n) {
        int count = 0;
        int flag = 1;
        while (flag != 0){
            if ((n & flag) != 0) count++;
            flag = flag << 1;
        }
        return count;
    }

    public static void main(String[] args) {
        System.out.println(new Test13().hammingWeight2(0));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章