码迷,mamicode.com
首页 > 其他好文 > 详细

Count 1 in Binary

时间:2015-11-13 12:59:49      阅读:209      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
};

 

Count 1 in Binary

标签:

原文地址:http://www.cnblogs.com/codingEskimo/p/4961806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!