[LintCode] Count 1 in Binary [典型位運算題目]

Problem

Count how many 1 in binary representation of a 32-bit integer.code

Example

Given 32, return 1it

Given 5, return 2io

Given 1023, return 9class

Challenge

If the integer is n bits with m bits. Can you do it in O(m) time?二進制

Note

這道題,Olivia給我解決了兩個疑問,還剩一個。首先是要用無符號右移運算符>>>,其次是能夠用一個不斷左移的二進制1做爲參照。那麼如何得到一個用1來進行補位的左移的1呢?
第一種解法,num右移,每次對末位進行比較,直到num爲0;
第二種解法,1左移,每次和num的第i位比較,直到i = 32;
第三種解法,num和num-1逐位與,去1,直到num爲0。im

Solution

1.vi

public class Solution {
    public int countOnes(int num) {
        int count = 0;
        while (num != 0) {
            count += (num & 1);
            num >>>= 1;
        }
        return count;
    }
};

2.while

public class Solution {
    public int countOnes(int num) {
        int count = 0;
        for(int i = 0 ; i < 32; i++) {
            if((num & (1<<i)) != 0)
                count++;
        }
        return count;
    }
}

3.co

public class Solution {
    public int countOnes(int num) {
        int count = 0;
        while (num != 0) {
            num &= num - 1;
            count++;
        }
        return count;
    }
}

// 1111 1110 1110
// 1110 1101 1100
// 1100 1011 1000
// 1000 0111 0000time

相關文章
相關標籤/搜索