Write a function with an input of an unsigned integer that returns the number of digits in its binary expression that is '1' (also known as Hamming weight).
Example 1: Input: 00000000000000000000000000001011
Output: 3 Explanation: There are three of the binary strings 00000000000000000000000000001011 input'1'。
Example 2: Input: 00000000000000000000000010000000
Output: 1 Explanation: There is a total of one of the input binary strings 00000000000000000000000010000000'1'。
Example 3: Input: 11111111111111111111111111111101
Output: 31 Explanation: The input binary string 11111111111111111111111111111101 has a total of 31 bits'1'。
Tip: Note that in some languages, such as j**a, there is no unsigned integer type. In this case, both the input and output will be specified as a signed integer type and should not affect your implementation, as the binary representation inside the integer is the same regardless of whether the integer is signed or unsigned.
In j**a, the compiler uses two's complement notation to represent signed integers. So, in Example 3 above, the input represents a signed integer -3.
Advanced: How will you optimize your algorithm if this function is called multiple times?
The gist of the bit arithmetic is that given an unsigned integer, return the number of 1s when it is used in binary tabs.
With a trick here, it's easy to find out. That's itn & n - 1)
YesElimination
n The principle of the last one 1.
Why the last 1 can be eliminated is actually relatively simple, everyone thinks for themselves.This way we can keep going
n = n & n - 1)
Until n === 0, there is no one 1 left. This timeHow many 1s we eliminated became a 1 at all, which means how many 1s there are in n
n & n - 1)
YesElimination
n The principle of the last one 1 simplifies operations.
bit operation.
Language support: JS, C++, Python, J**A
j**ascript code:
/* *lc app=leetcode id=191 lang=j**ascript * //** param n - a positive integer * return */var hammingweight = function (n) return count;};
c++ code:
class solution return count; }
python code:
class solution(object): def hammingweight(self, n): """ :type n: int :rtype: int """ count = 0 while n: n &= n - 1 count += 1 return count
j**a code:
public class solution }return count; }
Complexity analysisTime Complexity: $o(logn)$Space Complexity: $o(n)$ can be used to achieve the goal by bitwise operations. For example, an 8-bit integer 21:
c++ code:
const uint32_t odd_bit_mask = 0xaaaaaaaa;const uint32_t even_bit_mask = 0x55555555;const uint32_t odd_2bit_mask = 0xcccccccc;const uint32_t even_2bit_mask = 0x33333333;const uint32_t odd_4bit_mask = 0xf0f0f0f0;const uint32_t even_4bit_mask = 0x0f0f0f0f;const uint32_t odd_8bit_mask = 0xff00ff00;const uint32_t even_8bit_mask = 0x00ff00ff;const uint32_t odd_16bit_mask = 0xffff0000;const uint32_t even_16bit_mask = 0x0000ffff;class solution };