Leetcode 191. Number of 1 Bits

来源:互联网 发布:小学古诗大全软件 编辑:程序博客网 时间:2024/05/21 04:43

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

For example, the 32-bit integer ’11' has binary representation00000000000000000000000000001011, so the function should return 3.


解法一:O(1);

public class Solution{

     public int hammingWeight(int n){

           return Integer.bitCount(n);

     }

}


解法二:O(k)   k=1的个数

public class Solution{

      public int hammingWeight(int n){

             int num=0;

             while(n!=0){

             num+=  n&1;

             n>>>=1;//这里不能用>>  因为>>>移位以后不足的用0取代   而>>移位以后直接丢弃数据,不会补充

             }

             return num;

        }

}


解法三:O(log2(n))

public class Solution{

        public int hammingWeight(int n){

              int count =0;

              while(n>0) {

                  if(n%2 != 0)count ++;

                  n=n/2;

               }

              return count;

        }

}

0 0