2025-01-09 20:29:41 +08:00
< p > Given a positive integer < code > n< / code > , write a function that returns the number of < span data-keyword = "set-bit" > set bits< / span > in its binary representation (also known as the < a href = "http://en.wikipedia.org/wiki/Hamming_weight" target = "_blank" > Hamming weight< / a > ).< / p >
2022-03-27 20:56:26 +08:00
< p > < / p >
2023-12-09 18:42:21 +08:00
< p > < strong class = "example" > Example 1:< / strong > < / p >
2022-03-27 20:56:26 +08:00
2025-01-09 20:29:41 +08:00
< div class = "example-block" >
< p > < strong > Input:< / strong > < span class = "example-io" > n = 11< / span > < / p >
< p > < strong > Output:< / strong > < span class = "example-io" > 3< / span > < / p >
< p > < strong > Explanation:< / strong > < / p >
< p > The input binary string < strong > 1011< / strong > has a total of three set bits.< / p >
< / div >
2022-03-27 20:56:26 +08:00
2023-12-09 18:42:21 +08:00
< p > < strong class = "example" > Example 2:< / strong > < / p >
2022-03-27 20:56:26 +08:00
2025-01-09 20:29:41 +08:00
< div class = "example-block" >
< p > < strong > Input:< / strong > < span class = "example-io" > n = 128< / span > < / p >
< p > < strong > Output:< / strong > < span class = "example-io" > 1< / span > < / p >
< p > < strong > Explanation:< / strong > < / p >
< p > The input binary string < strong > 10000000< / strong > has a total of one set bit.< / p >
< / div >
2022-03-27 20:56:26 +08:00
2023-12-09 18:42:21 +08:00
< p > < strong class = "example" > Example 3:< / strong > < / p >
2022-03-27 20:56:26 +08:00
2025-01-09 20:29:41 +08:00
< div class = "example-block" >
< p > < strong > Input:< / strong > < span class = "example-io" > n = 2147483645< / span > < / p >
< p > < strong > Output:< / strong > < span class = "example-io" > 30< / span > < / p >
< p > < strong > Explanation:< / strong > < / p >
< p > The input binary string < strong > 1111111111111111111111111111101< / strong > has a total of thirty set bits.< / p >
< / div >
2022-03-27 20:56:26 +08:00
< p > < / p >
< p > < strong > Constraints:< / strong > < / p >
< ul >
2025-01-09 20:29:41 +08:00
< li > < code > 1 < = n < = 2< sup > 31< / sup > - 1< / code > < / li >
2022-03-27 20:56:26 +08:00
< / ul >
< p > < / p >
< strong > Follow up:< / strong > If this function is called many times, how would you optimize it?