Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011
, so the function should return 3.
題目標籤:Bit Manipulation
這題給我們一個integer,讓我們找到bits中1的個數,利用 & 1 判斷bit是不是1,然後利用 >> 來移動bits。
Java Solution:
Runtime beats 16.07%
完成日期:06/26/2017
關鍵詞:Bit Manipulation
關鍵點:用 & 拿到bit, 用 >> 來移動bits
public class Solution
{
// you need to treat n as an unsigned value
public int hammingWeight(int n)
{
int res = 0; for(int i=0; i<32; i++)
{
if((n & 1) == 1) // meaning the most right bit is 1
res++; n = n >> 1; // shift to right 1 bit
} return res;
}
}
參考資料: N/A
LeetCode 演算法題目列表 - LeetCode Algorithms Questions List