Sword refers to Offer 15 (bit operation 1). The number of 1 in binary

Problem Description:

Write a function that takes as input an unsigned integer (as a binary string) and returns the number of '1' digits in its binary representation (also known as the Hamming weight).

hint:

  • Note that in some languages ​​(like Java), there is no unsigned integer type. In this case both input and output will be specified as signed integer types and should not affect your implementation since the internal binary representation of an integer is the same whether it is signed or unsigned.
  • In Java, the compiler uses two's complement notation to represent signed integers. So, in example 3 above , the input represents a signed integer -3.

Example:

输入:n = 11 (控制台输入 00000000000000000000000000001011)
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'
输入:n = 128 (控制台输入 00000000000000000000000010000000)
输出:1
解释:输入的二进制串 00000000000000000000000010000000 中,共有一位为 '1'

Input: n = 4294967293 (console input 1111111111111111111111111101, n = -3 in some languages)
Output: 31
Explanation: In the input binary string 111111111111111111111111111101, a total of 31 bits are '1'.

Problem-solving ideas:Idea link

bit by bit judgment

According to the definition of AND operation, assuming binary number n, then:

  • ​ If n & 1 = 0, then the rightmost bit of n binary is 0;
  • ​ If n & 1 = 1, then the rightmost bit of n binary is 1.

According to the above characteristics, consider the following loop judgment:

  • ​ Determine whether the rightmost bit of n is 1, and count according to the result.
  • ​ Shift n to the right by one bit (this question requires the number n to be regarded as an unsigned number, so use an unsigned right shift operation).

Algorithm flow :

  • ​ Initialize the quantity statistics variable number = 0.
  • ​ Circular bit-by-bit judgment: jump out when n = 0.
  • ​ number += n & 1: If n & 1 = 1, add one to the statistics number.
  • ​ n >>>= 1: Shift the binary number n unsigned to the right by one bit (unsigned right shift in Java is ">>>").
  • ​ Return the statistical quantity number.

Code

public class Solution {
    
    
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
    
    
        int number = 0;
        while(n != 0){
    
    
            int m = n & 1;
            number += m;
            //无符号右移>>>:正数与右移规则一样,负数的无符号右移,就是相应的补码移位所得,在高位补0即可
            n >>>= 1;
        }
        return number;
    }
}

Guess you like

Origin blog.csdn.net/Royalic/article/details/120005074