面试题15. 二进制中1的个数

https://leetcode-cn.com/problems/er-jin-zhi-zhong-1de-ge-shu-lcof/solution/mian-shi-ti-15-er-jin-zhi-zhong-1de-ge-shu-wei-yun/

func hammingWeight(_ n: Int) -> Int {
    var result = 0
    var N = n
    //n&(n−1): n最右边的1变成0,其余不变。
    while N > 0 {
        result = result + 1
        N = N  & (N - 1)
    }
    return result
}

你可能感兴趣的:(面试题15. 二进制中1的个数)