二进制中1的个数 也称为汉明重量 (leetcode 191)

一:解题思路

第一种方法:用一个数字1与原始数字进行按位&,如果不为0,计数器加1,然后数字1向左移动一位,继续检查原始数字的倒数第二位,直到数字1向左移动变为0。Time:O(m),m表示原始数字中二进制1的个数。Space:O(1)

第一种方法变体:判断(n&1) ==1 ? counts+=1 ,n>>1

第二种方法:第二种相对第一种较快的方法。原始数字不为0,加1。然后原始数字n和数字n-1相与,依次循环,直到数字n变为。 记住一个结论,n=n&(n-1) 是将数字n二进制中最后一个1变成0。

二:完整代码示例 (C++版和Java版)

方法一C:

int hammingWeight(uint32_t n) {
    int mask = 1;
    int count = 0;

    while (mask != 0) {
        if ((mask & n) != 0) count++;
        mask <<= 1;
    }

    return count;
}

方法二C:

int hammingWeight(uint32_t n) {
    int count = 0;

    while (n != 0) {
        count++;

        n &= (n-1);
    }

    return count;
}

 

方法一C++:

class Solution 
{
public:
    int hammingWeight(uint32_t n) 
    {
        int num = 1;
        int count = 0;

        while (num != 0)
        {
            if ((n&num) != 0) count++;

            num <<= 1;
        }

        return count;
    }
};

 

方法一变体:

class Solution {
public:
    int hammingWeight(uint32_t n) {
        int counts = 0;

        while (n != 0) {
            if ((n & 1) == 1) counts += 1;
            n >>= 1;
        }

        return counts;
    }
}

 

方法二C++:

class Solution 
{
public:
    int hammingWeight(uint32_t n) 
    {
        int count = 0;

        while (n != 0)
        {
            count++;

            n &= (n-1);
        }

        return count;
    }
};

 

方法一Java:

public class Solution
{
    public int hammingWeight(int n)
    {
          int num=1;
          int count=0;
          
          while(num!=0)
          {
              if((num&n)!=0) count++;
              
              num<<=1;
          }
          
          return count;
    }
}

方法二Java:

public class Solution
{
    public int hammingWeight(int n)
    {
          int count=0;

          while(n!=0)
          {
              count++;
              
              n&=(n-1);
          }

          return count;
    }
}

 

方法一Python: 

 

 

方法二Python:

class Solution:
    def hammingWeight(self, n: int) -> int:
        count=0
        
        while n:
            count+=1
            n&=(n-1)
        return count

 

posted @ 2020-03-15 15:34  repinkply  阅读(366)  评论(0)    收藏  举报