Buckle force - the number of bits 1

A write function, the input is an unsigned integer, which returns the number of digits in the binary representation of the number '1' (also called Hamming weight).

 

Example 1:

Input: 00000000000000000000000000001011
Output: 3
Explanation: 00000000000000000000000000001011 input binary string, a total of three to '1'.

Example 2:

Input: 00000000000000000000000010000000
Output: 1
Explanation: 00000000000000000000000010000000 input binary string, there is a '1'.

Example 3:

Input: 11111111111111111111111111111101
Output: 31
Explanation: 11111111111111111111111111111101 input binary string, a total of 31 to '1'.

 

Note:

    Please note that in some languages (such as Java), there is no unsigned integer type. In this case, the input and output will be designated as a signed integer type, and should not affect your implementation, because both the integer is signed or unsigned, its binary representation of the interior is the same.
    In Java, the compiler uses the twos complement notation to represent signed integers. Thus, in the above example 3, the input represents a signed integer -3.

 

Advanced:
If you repeatedly call this function, you will how to optimize your algorithm?

Source: stay button (LeetCode)
Link: https: //leetcode-cn.com/problems/number-of-1-bits
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

 

 

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

 

Guess you like

Origin www.cnblogs.com/JAYPARK/p/11222886.html
Recommended