leetcode No191. Number of 1 Bits
来源:互联网 发布:会议速记软件 编辑:程序博客网 时间:2024/06/07 03:33
Question:
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.
求二进制中1的个数
Algorithm:
1、把1不断移位和num &,并不断计数可以得到1的个数
2、假设最右边的1在第m位,那么n-1的第m位为1,第m-1位到最右都为1,而n的第m位为1,第m-1位到最右都为0,这样n&(n-1)后,第m位到最右就全为0,计数+1。
循环这样的操作,直到n为0,结束循环。
Code:
算法1:
class Solution {public: int hammingWeight(uint32_t n) { int count=0; uint32_t flag=1; while(flag) { if(flag & n) count++; flag=flag<<1; } return count; }};算法2:
class Solution {public: int hammingWeight(uint32_t n) { int count=0; while(n) { count++; n=(n-1)&n; } return count; }};
0 0
- leetcode No191. Number of 1 Bits
- leetcode:bits:Number of 1 Bits(191)
- LeetCode:Number of 1 Bits
- LeetCode-Number of 1 Bits
- leetcode: Number of 1 Bits
- LeetCode Number of 1 Bits
- Leetcode: Number of 1 Bits
- Leetcode--Number of 1 Bits
- [LeetCode] Number of 1 Bits
- [leetcode]Number of 1 Bits
- Leetcode-Number of 1 Bits
- LeetCode Number of 1 Bits
- LeetCode-Number of 1 Bits
- [Leetcode] Number of 1 Bits
- [Leetcode]Number of 1 Bits
- leetcode--Number of 1 Bits
- leetcode:Number of 1 Bits
- 【leetcode】Number of 1 Bits
- OpenLayers 3 +天地图展示
- python笔记
- 链接的请求方式 是get
- java中final的作用
- 读书笔记:W3CSchool学习教程-C#教程(下)
- leetcode No191. Number of 1 Bits
- Linux基本知识
- SQL Server 中添加表注释.
- Openwrt启动流程及启动脚本分析
- bootstrap下拉框
- HDU 5514 Frogs(巧妙地容斥)
- mysql主从配置和数据迁移
- java之redis篇(spring-data-redis整合)
- IE浏览器中表单控件的样式