191. Number of 1 Bits

来源:互联网 发布:2017网络语 编辑:程序博客网 时间:2024/06/05 14:11

191. Number of 1 Bits

Description:
Write a function that takes an unsigned integer and returns the number of ’1’ bits it has (also known as the Hamming weight).
Example:
For example, the 32-bit integer ’11’ has binary representation 00000000000000000000000000001011, so the function should return 3.
Link:
https://leetcode.com/problems/number-of-1-bits/
Analysis:
这道题解法还是挺多的,参考:
A. 《编程之美》 2.1 求二进制数中1的个数
B. 博文:Hamming Weight的算法分析http://blog.csdn.net/gsyzhu/article/details/8095174
Source Code(C++):

#include <iostream>using namespace std;/******************解法一:除2取余法***********************************//*class Solution {public:    int hammingWeight(unsigned int n) {        int ans=0;          while(n) {            if (n%2 == 1) {                ++ans;            }            n /= 2;        }        return ans;    }};*//******************解法二:位操作法(原理同一)***********************************//*class Solution {public:    int hammingWeight(unsigned int n) {        int ans=0;          while(n) {            ans += n&0x01;            n >>= 1;        }        return ans;    }};*//******************解法三***********************************//*class Solution {public:    int hammingWeight(unsigned int n) {        int ans=0;          while(n) {            n &= (n-1);            ans++;        }        return ans;    }};*//************************解法四:查表法,一般不太实用,此处省略************************************//******************解法五***********************************/class Solution {public:    int hammingWeight(unsigned int n) {        const unsigned long int m2 = 0x55555555;        const unsigned long int m4 = 0x33333333;        const unsigned long int m8 = 0x0f0f0f0f;        const unsigned long int m16 = 0x00ff00ff;        const unsigned long int m32 = 0x0000ffff;        n = (n&m2) + ((n>>1)&m2);        n = (n&m4) + ((n>>2)&m4);        n = (n&m8) + ((n>>4)&m8);        n = (n&m16) + ((n>>8)&m16);        n = (n&m32) + ((n>>16)&m32);        return n;//      cout << sizeof(unsigned long int);    }};int main() {    Solution sol;    cout << sol.hammingWeight(10);    return 0;}
0 0
原创粉丝点击