LeetCode -- Number of 1 Bits
2015-11-21 10:24
302 查看
题目描述:
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的个数。
思路:
对于整数n,从n开始对n和n-1做与运算然后赋值给n。即,n=n&n-1。直到n等于n为止。能做多少次运算就说明有多少个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的个数。
思路:
对于整数n,从n开始对n和n-1做与运算然后赋值给n。即,n=n&n-1。直到n等于n为止。能做多少次运算就说明有多少个1。
实现代码:
public class Solution { public int HammingWeight(uint n) { int count; for (count=0; n > 0 ; count++){ n &= n-1; } return count; } }
相关文章推荐
- windows下使用cx_freeze将Python程序打包成exe可执行文件
- HDU 1034 Candy Sharing Game
- Python正则表达式学习小结
- Ubuntu环境下利用Python3+PyQt5+Eric6进行GUI编程
- git/github轻松上传本地项目
- activity创建与隐式启动
- 为什么要写设计文档(英文版)
- 搞IT,还是需要有自己的博客
- LeetCode -- Minimum Size Subarray Sum
- hdoj DeBruijin 2894 (dfs&&欧拉回路转化) 好题
- listview和其中的item中的view焦点冲突解决方案
- 华为OJ中级-计算日期到天数转换
- 各种坑的笔记
- win10 1511(win10 TH2)如何调整开始屏幕磁贴大小?
- 单片机 MSP430 模拟IIC编程(2)
- RDBMS DBMS MS DB
- 《浪潮之巅》随想
- kaptcha验证码使用
- OpenGL教程翻译 第二十五课 天空盒
- flask-学习目的与开发环境搭建