(Java)leetcode-191 Number of 1 Bits(带符号右移与无符号右移的区别)

题目

1的位数

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

Example 1:

Input: 00000000000000000000000000001011
Output: 3

Explanation: The input binary string 00000000000000000000000000001011 has a total of three ‘1’ bits.
Example 2:

Input: 00000000000000000000000010000000
Output: 1

Explanation: The input binary string 00000000000000000000000010000000 has a total of one ‘1’ bit.
Example 3:

Input: 11111111111111111111111111111101
Output: 31

Explanation: The input binary string 11111111111111111111111111111101 has a total of thirty one ‘1’ bits.

Note:

Note that in some languages such as Java, there is no unsigned integer type. In this case, the input will be given as signed integer type and should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 3 above the input represents the signed integer -3.

Follow up:

If this function is called many times, how would you optimize it?

思路

涉及到二进制,自然想到位运算。在循环中,通过将目标与1进行按位与(&)运算,可以判断最低位上的数字是否为1,接下来将目标向右移,进而判断高一位上的数字是否为1,整个过程中对1的位数进行计数。
时间复杂度O(1)。

代码

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int res = 0;
        while(n != 0){
        	if((n & 1) != 0){
        		res++;
        	}
        	n >>>= 1;
        }
        return res;
    }
}

提交结果

Runtime: 0 ms, faster than 100.00% of Java online submissions for Number of 1 Bits.
Memory Usage: 32.1 MB, less than 100.00% of Java online submissions for Number of 1 Bits.

小结

值得注意的是>>与>>>的区别。
“>>”是带符号右移——

  • 正数右移时,低位溢出,高位补0
  • 负数右移时,低位溢出,高位补1

“>>>”是无符号右移——

无论是正数还是负数,右移时低位溢出,高位通通补0。

在本题中,由于需要对整数的二进制表示中的所有1进行统计(包括符号位),那么由于“>>”带符号右移时,在负数的情况下由于符号位补1,会影响1的数量。因此。这里只能使用“>>>”无符号右移。

猜你喜欢

转载自blog.csdn.net/z714405489/article/details/88618100