【一天一道LeetCode】#191. Number of 1 Bits
2016-07-14 21:10
267 查看
一天一道LeetCode
本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github欢迎大家关注我的新浪微博,我的新浪微博
欢迎转载,转载请注明出处
(一)题目
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的个数解题思路:剑指offer上的老题了。
把一个整数减去1,然后与原整数做与运算,会把该整数最右边的一个1变成0,要计算1的个数,就循环上述操作,直到这个数为0为止。
class Solution { public: int hammingWeight(uint32_t n) { int num = n; int count = 0; while(n) { n = n&(n-1); count++; } return count; } };
相关文章推荐
- 【一天一道LeetCode】#231. Power of Two
- CodeForces 525D Arthur and Walls
- 结构之法and算法之道(合集)
- C++ 模板类的实现为何放在.h中
- linux awk命令详解
- malloc/free new/delete
- Java实现链表反转
- 【一天一道LeetCode】#326. Power of Three
- 【一天一道LeetCode】#326. Power of Three
- PKI证书签发系统(web版)
- hdu 2044
- Android学习路线总结,绝对干货
- openfire presence研究
- Android源码学习之浅析SystemServer脉络
- 洛谷 P1969 [NOIP2013 D2T1] 积木大赛
- Android中Socket通信readline()方法阻塞问题
- 指针与引用,宏与预处理,define与tpyedef
- Spring学习笔记三: 通过注解配置Bean
- java之小数位截取
- Spring学习笔记三: 通过注解配置Bean