Data Structure & Algorithm: Level-1 Problem #16. Hamming Weight

The Hamming weight of a string is the number of symbols that are different from the zero-symbol of the alphabet used. It is thus equivalent to the Hamming distance from the all-zero string of the same length. For the most typical case, a string of bits, this is the number of 1’s in the string, or the digit sum of the binary representation of a given number and the ℓ₁ norm of a bit vector. In this binary case, it is also called the population count, popcount, sideways sum, or bit summation.

Given an unsigned integer and find out the total number of 1 bits it has in binary format.

Sample Input: 327

Sample Output: 5

With the sample input, number 327 in binary format is 0b101000111. So it’s hamming weight is 5.


数据结构和算法:初级练习题 #16 – 汉明重量


汉明重量是一串符号中非零符号的个数。因此它等同于同样长度的全零符号串的汉明距离。在最为常见的数据位符号串中,它是1的个数。

汉明重量是以理查德·卫斯里·汉明的名字命名的,它在包括信息论编码理论密码学等多个领域都有应用。在密码学以及其它应用中经常需要计算数据位中1的个数,针对如何高效地实现人们已经广泛地进行了研究。一些处理器使用单个的命令进行计算,另外一些根据数据位向量使用并行运算进行处理。对于没有这些特性的处理器来说,已知的最好解决办法是按照树状进行相加。

给定一个整数 n,计算它的汉明重量。

输入样例: 327

输出样例: 5

十进制数字 327 用二进制表示是 0b101000111,所以它的汉明重量是 5。


Python Solution

Hamming Weight