[leetcode] 191. Number of 1 Bits 解题报告
2016-05-19 07:17
507 查看
题目链接: https://leetcode.com/problems/number-of-1-bits/
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.
思路: 按位与计算1的个数
代码如下:
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的个数
代码如下:
class Solution { public: int hammingWeight(uint32_t n) { unsigned int cnt = 0, num; for(int i = 0; i< 32; i++) { num = 1<<i; cnt += (num&n)?1:0; } return cnt; } };
相关文章推荐
- 小酌重构系列[16]——引入契约式设计
- 小酌重构系列[16]——引入契约式设计
- linux grep egrep fgrep bash条件判断 bash测试 if 条件判断
- 甲骨文联席 CEO 否认收购 Sun 是为了提起诉讼
- LeetCode 21. Merge Two Sorted Lists(合并链表)
- JVM调优浅谈
- 01.LoT.UI 前后台通用框架分解系列之——小图片背景全屏显示(可自动切换背景)
- pg_prewarm 与 pgfincore的区别
- SDUT 2410 Mine Number 2012年山东省第三届ACM大学生程序设计竞赛题
- 15分钟弄懂 const 和 #define
- 证书相关
- LeetCode 20. Valid Parentheses(括号校验)
- complex类 序列化时 IsRequired = true 问题
- 【华为OJ】【084-求最大连续bit数】
- 编程思想之多线程与多进程(4)——C++中的多线程
- 【华为OJ】【083-计算字符串的相似度】
- 还需要补充很多知识
- LeetCode 19. Remove Nth Node From End of List(删除链表)
- (加精)AndrodStudio 极光推送 推送类手写版加精Demo 续写!!!
- leetcode 11 in c++