首页 > 其他 > 详细

LeetCode -- Number of 1 Bits

时间:2015-11-21 11:53:41      阅读:130      评论:0      收藏:0      [点我收藏+]
题目描述:


Write a function that takes an unsigned integer and returns the number of ’1‘ bits it has (also known as the Hamming weight).


For example, the 32-bit integer ’11‘ has binary representation 00000000000000000000000000001011, so the function should return 3.




本题依然属于一道位运算的题目,输入一个无符号的整数,判断出1的个数。


思路:
对于整数n,从n开始对n和n-1做与运算然后赋值给n。即,n=n&n-1。直到n等于n为止。能做多少次运算就说明有多少个1。


实现代码:

public class Solution {
    public int HammingWeight(uint n) {
        int count;
		for (count=0; n > 0 ; count++){
			n &= n-1;
		}
		return count;
    }
}


LeetCode -- Number of 1 Bits

原文:http://blog.csdn.net/lan_liang/article/details/49962407

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!