[LintCode] Count 1 in Binary

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

Example

Given 32, return 1

Given 5, return 2

Given 1023, return 9

思路:

知识点: n & (n - 1) 使得从右边数最后一个1变为0

x & (x - 1) 用于消去x最后一位的1, 比如x = 12, 那么在二进制下就是(1100)2

x           = 1100
x - 1       = 1011
x & (x - 1) = 1000
反复对做 x & (x - 1) 一直到x为0为止,数一数取了多少次就可以知道有多少位是1

solution 1
public class Solution {
    /*
     * @param num: An integer
     * @return: An integer
     */
    public int countOnes(int num) {
        // write your code here
        int count = 0;
        while (num != 0) {
            num = (num & num - 1);
            count++;
        }
        return count;
    }
};

solution 2
public class Solution {
    /**
     * @param num: an integer
     * @return: an integer, the number of ones in num
     */
    
    /***
     * Bit Opperation:
     * &:  1 & 1 = 1; 1 & 0 = 0; 0 & 0 = 0
     * ~:   ~1 = 0; ~0 = 1
     * |:  1 | 1 = 1; 1 | 0 = 1; 0 | 0 = 0
     * ^:  1 ^ 1 = 0; 1 ^ 0 = 1; 0 ^ 0 = 0
     * <<: left shift 00000001 << 3 = 00001000
     * >>: right shift The first bit is sign, it will got shift. 
     * knowledge: http://sys.cs.rice.edu/course/comp314/10/p2/javabits.html
     ***/
    
    public int countOnes(int num) {
        // write your code here
        int count = 0;
        for (int i = 0; i < 32; i++){
            if ((num & (1 << i))!= 0){ //1 <<i only have one bit set to 1, the rest is 0, & will turn other bits to be 0. So whether it will 0 all counts on what "num" has on the same bit poistion.  
                count++;
            } 
        }
        return count;
    }
};
 

 

posted on 2015-11-13 12:41  codingEskimo  阅读(134)  评论(0)    收藏  举报

导航