你好,欢迎来到电脑编程技巧与维护杂志社! 杂志社简介广告服务读者反馈编程社区  
合订本订阅
 
 
您的位置:技术专栏 / C专栏
LeetCode -- Number of 1 Bits
 
题目描述:


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

  推荐精品文章

·2024年2月目录 
·2024年1月目录
·2023年12月目录
·2023年11月目录
·2023年10月目录
·2023年9月目录 
·2023年8月目录 
·2023年7月目录
·2023年6月目录 
·2023年5月目录
·2023年4月目录 
·2023年3月目录 
·2023年2月目录 
·2023年1月目录 

  联系方式
TEL:010-82561037
Fax: 010-82561614
QQ: 100164630
Mail:gaojian@comprg.com.cn

  友情链接
 
Copyright 2001-2010, www.comprg.com.cn, All Rights Reserved
京ICP备14022230号-1,电话/传真:010-82561037 82561614 ,Mail:gaojian@comprg.com.cn
地址:北京市海淀区远大路20号宝蓝大厦E座704,邮编:100089