191. Number of 1 Bits
2016-05-19 12:00
239 查看
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
so the function should return 3.
思路:愚蠢如我,一开始只想到把十进制转换成二进制然后数数。后来又想利用2^n-1的规律。
然后一看答案直接给跪。
n&n-1,就是这么简单。每次n&n-1都会去掉一个1。
tips: 关于uint32_t:uint8_t,uint16_t,uint32_t等都不是什么新的数据类型,它们只是使用typedef给类型起的别名,新瓶装老酒的把戏。
weight).
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011,
so the function should return 3.
思路:愚蠢如我,一开始只想到把十进制转换成二进制然后数数。后来又想利用2^n-1的规律。
然后一看答案直接给跪。
n&n-1,就是这么简单。每次n&n-1都会去掉一个1。
tips: 关于uint32_t:uint8_t,uint16_t,uint32_t等都不是什么新的数据类型,它们只是使用typedef给类型起的别名,新瓶装老酒的把戏。
class Solution { public: int hammingWeight(uint32_t n) { int res=0; while(n){ n&=n-1; res++; } return res; } };
相关文章推荐
- html点击复制到剪贴板
- @Transactional
- wordpress百度星火计划2.0项目怎么添加标签
- hdu1002 A + B Problem II(高精度加法)
- Tomcat二级域名共享SESSION
- shell中job管理
- Linux 下配置 phpredis 的过程和遇到的问题
- 万能的HashMap
- 知道这20个正则表达式,能让你少写1,000行代码
- Pull方式解析XML文件
- Spark-Spark Streaming例子整理(三)
- Linux下安装Redis
- spark 环境搭建及几种模式测试
- Volley简单总结
- Python接口测试
- Why use @PostConstruct?
- php 字符串函数
- Android学习路线
- angular中的等号(==)判定
- jquery数组删除指定元素的方法:grep()