题目描述

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的数时会报错“过大的整数”。

相关文章:

  • 2021-07-11
  • 2022-12-23
  • 2021-10-29
  • 2022-01-22
  • 2021-10-28
  • 2021-08-17
  • 2021-05-19
  • 2021-09-09
猜你喜欢
  • 2022-01-11
  • 2022-01-09
  • 2022-03-07
  • 2021-07-02
  • 2021-12-04
相关资源
相似解决方案