(LeetCode 191) Number of 1 Bits
来源:互联网 发布:网页设计排版软件 编辑:程序博客网 时间:2024/06/05 05:57
题:
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进行计数。
solution:
这道题主要一个陷阱就是,题目要求计算的是该整数无符号二进制中的1的个数,但是整数实际上在计算机中是按照有符号二进制补码存储会有一位符号位,所以当输入为
我们只需要把输入的32位无符号整数用long类型存储,这样可以避免数据位被转化成符号位。
class Solution {public: int hammingWeight(uint32_t n) { long m = n; int count=0; int i=0; while((m>>i)>0) {if((m>>i)&1==1)count++;i++;} return count; }};
1 0
- leetcode:bits:Number of 1 Bits(191)
- [Leetcode 191, Easy] Number of 1 Bits
- leetCode #191 number of 1 bits
- LeetCode 191 Number of 1 Bits
- Leetcode NO.191 Number of 1 Bits
- [LeetCode][191][Number of 1 Bits]
- [leetcode 191]Number of 1 Bits
- LeetCode(191) Number of 1 Bits
- LeetCode #191 Number of 1 Bits
- LeetCode 191: Number of 1 Bits
- LeetCode 191 Number of 1 Bits
- Leetcode #191 Number of 1 Bits
- LeetCode 191 Number of 1 Bits
- LeetCode 191: Number of 1 Bits
- leetcode[191]:Number of 1 Bits
- leetcode-191-Number of 1 Bits
- leetcode 191:Number of 1 Bits
- leetcode: (191) Number of 1 Bits
- Flume:本地文件到Kafka
- Mybatis学习记录(三)--Mybatis配置文件详解
- activity与fragment通信汇总
- HDU 4622 Reincarnation 后缀自动机
- Intent详解
- (LeetCode 191) Number of 1 Bits
- CLM研究
- [POJ 3276] Face The Right Way (翻转问题+技巧)
- Error:Configuration with name 'default' not found. 解决办法
- java并发的线程安全单例模式
- spoj HS12MBR - Minimum Bounding Rectangle
- MSSQL 构建日期范围内的连续月份或日期(不借助系统表的方法)
- IntelliJ IDEA 使用心得与常用快捷键
- Flume的可靠性保证:故障转移、负载均衡