首页 > 其他 > 详细

Count 1 in Binary

时间:2015-11-13 12:59:00      阅读:321      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!