191. 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).

写一个函数,读入无符号整数,返回它包含的'1'位的个数

Example 1:

Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011 

Example 2:

Input: 128
Output: 1
Explanation: Integer 128 has binary representation 00000000000000000000000010000000
 

public static int hammingWeight(int n) {
	int ones = 0;
    	while(n!=0) {
    		ones = ones + (n & 1);
    		n = n>>>1;
    	}
    	return ones;
}
  • An Integer in Java has 32 bits, e.g. 00101000011110010100001000011010.  java中的integer类型有32位
  • To count the 1s in the Integer representation we put the input int n in bit AND with 1 (that is represented as 00000000000000000000000000000001, and if this operation result is 1,that means that the last bit of the input integer is 1. Thus we add it to the 1s count.为了数1的个数,我们把n和1做位与运算,如果结果是1,表示最后一位是1,1的个数加1.

ones = ones + (n & 1);

&同为1时为1,否则为0(来源:https://blog.csdn.net/solo_two/article/details/51543957)

|同为0时为0,否则为1

3&5则

 0011

&0101

 0001

等于1


  • Then we shift the input Integer by one on the right, to check for the next bit.接下来我们把整数右移一位,来检查接下来一位

n = n>>>1;

>>:带符号右移。正数右移高位补0,负数右移高位补1。比如:

4 >> 1,结果是2;-4 >> 1,结果是-2。-2 >> 1,结果是-1。

>>>:无符号右移。无论是正数还是负数,高位通通补0。

对于正数而言,>>和>>>没区别。

本段来源 https://www.cnblogs.com/565261641-fzh/p/7686757.html

We need to use bit shifting unsigned operation >>> (while >> depends on sign extension)

  • We keep doing this until the input Integer is 0.

In Java we need to put attention on the fact that the maximum integer is 2147483647. Integer type in Java is signed and there is no unsigned int. So the input 2147483648 is represented in Java as -2147483648 (in java int type has a cyclic representation, that means Integer.MAX_VALUE+1==Integer.MIN_VALUE).
This force us to use

n!=0

in the while condition and we cannot use

n>0

because the input 2147483648 would correspond to -2147483648 in java and the code would not enter the while if the condition is n>0 for n=2147483648.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值