题目链接

位1的个数

题目描述

image.png

实现代码

思路:运用了位运算的思想,循环 n &= n-1,直至n为0;

实现代码如下:

  1. public class Solution {
  2. // you need to treat n as an unsigned value
  3. public int hammingWeight(int n) {
  4. int result = 0;
  5. while(n != 0) {
  6. n &= n-1;
  7. result++;
  8. }
  9. return result;
  10. }
  11. }