算法系列——Number of 1 Bits
来源:互联网 发布:html input value js 编辑:程序博客网 时间:2024/06/05 09:01
题目描述
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.
解题思路
考察位操作,二进制位 0或1 与1 进行& 与操作 得到它本身。
0&1=0 1&1=1
然后右移操作可以得到 二进位的下一位, 例如 111>>>1=011
011&001=001
结合与操作和移位操作 可以得到所有1的个数。
程序实现
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int count=0; while(n!=0){ count+=n&1; //>>> 无符号右移,忽略符号位,空位都以0补齐 n>>>=1; } return count; }}
阅读全文
0 0
- 算法系列——Number of 1 Bits
- LeetCode191——Number of 1 Bits
- LeetCode191—Number of 1 Bits
- Number of 1 bits(算法练习)
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- Number of 1 Bits
- poj 3281 拆点最大流
- 机器学习-线性回归-最小二乘法
- MYSQL学习笔记(五)用通配符进行过滤
- 几何HDU5858
- android fastboot oem 命令
- 算法系列——Number of 1 Bits
- 使用Maven在Eclipse中创建Web项目
- 图片压缩--鲁班
- HDU-1465 不容易系列之一
- 关于http url中特殊符号的记录
- 集合复习
- [译]The Python Tutorial#2. Using the Python Interpreter
- ioctl的cmd不能为2
- POJ 2385 Apple Catching(牛吃苹果)