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
- 191.Number of 1 Bits
- 191.Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191. Number of 1 Bits
- 191.Number of 1 Bits
- 距离度量
- spring源码剖析(八)spring整合mybatis原理
- [图论] zoj1015
- IO流
- Kmp算法
- 191. Number of 1 Bits
- Java&Python操作WebHDFS
- 实现一个简单Socket通信示例
- Spark Streaming源码解读之RDD生成全生命周期详解
- 第11周补充(3)点派生时间类
- iOS 蓝牙开发(二)iOS 连接外设的代码实现
- 镜花水月,过不留痕————铭记那些给我们带来进步的C语言小难题<2>
- Java使用quartz实现作业调度
- java中的Clone(深拷贝,浅拷贝)