星期六, 三月 05, 2016

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).

 

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

 

解题思路:

1bit manipulate  利用n&(n-1)快速去掉最低位的1.

2、使用c++ stl中的bitset类型,将其转换为32位的二进制,利用count方法得到1的个数

3、已知输入为32位无符号的整数,可以知道只要循环32次,求每位是否为1.

#include<stdint.h>

#include<bitset>

using namespace std;

class Solution {

public:

    // 8ms

  //  int hammingWeight(uint32_t n) {

        //bitset<32>ans(n);

        //return ans.count();

  //  }

    // 8ms

    int hammingWeight(uint32_t n) {

        int cnt=0;

        for(;n;n>>=1){

            if(n&1)cnt++;

        }

        return cnt;

    }

    // 4ms

    int hammingWeight(uint32_t n) {

        int cnt = 0;

        for(; n; n >>= 1)

            if(n&1) ++cnt;

        return cnt;

    }

};

 

没有评论:

发表评论