LeetCode 191----Number of 1 Bits
2015-09-16 19:12
423 查看
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.
思路:
判断输入数据是否为0,不为0时:
输入数据和1与,结果不为0时,表示末尾数字为1;
当结果为0时,表示末尾数字为0;
右移输入数据,循环和1与比较,直到数据为0退出。
weight).
For example, the 32-bit integer ’11' has binary representation
00000000000000000000000000001011,
so the function should return 3.
思路:
判断输入数据是否为0,不为0时:
输入数据和1与,结果不为0时,表示末尾数字为1;
当结果为0时,表示末尾数字为0;
右移输入数据,循环和1与比较,直到数据为0退出。
class Solution { public: int hammingWeight(uint32_t n) { int num=0; while(n!=0) { if(n&1) num++; //n=n/2;<span style="white-space:pre"> </span>//右移一位相当于除2 n=n>>1; } return num; } };
相关文章推荐
- app后台运行
- 使用Genymotion调试出现错误INSTALL_FAILED_CPU_ABI_INCOMPATI
- Ubuntu中 JDK的安装和卸载
- 【BZOJ2697】特技飞行
- ng-repeat出现环路输出Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique
- Qt 学习之路:文件
- 初步swift语言学习笔记6(ARC-自己主动引用计数,内存管理)
- 惠普、我与JAVA
- 天声人語 20150916
- 无向图的最小生成树(prim算法)
- 《他的国》读后感(2)
- Linux共享库so文件创建与使用
- 复习排序-希尔排序
- Android Studio App文件夹下这个Module的gradle配置文件
- java多线程结合单例模式实例,简单实用易理解
- set集合 // 生成10-20,之间的10个随机数,要求不能重复
- JS中showModalDialog 详细使用
- 将本地图片文件写到模拟器的相册中
- C++ 单例模式
- 通过读取excel数据和mysql数据库数据做对比(二)-代码编写测试