LeetCode 191. Number of 1 Bits

题目描述

Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

实例

Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011

代码

public class Solution {
    // you need to treat n as an unsigned value
    public int hammingWeight(int n) {
        int count=0;
        while (n!=0)
        {
            n=n&(n-1);
            count++;
        }
        return count;
    }
}

分析

  1. 使用n=n&(n-1);可以将n的最后一个1变为0,循环直至n为0即可。
  2. 若使用移位操作会超时。
  3. 输入超过int的数时会报错“过大的整数”。
原文地址:https://www.cnblogs.com/l-h-x/p/9558802.html