[LeetCode][数论]Number of 1 Bits
2016-03-24 15:44
579 查看
题目描述:
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-1会使原n中1的个数-1,基于这个信息我们可以判断从n到0需要几次n&n-1,这是一个问题的转换过程,不必硬性计算32位的内容
代码实现:
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-1会使原n中1的个数-1,基于这个信息我们可以判断从n到0需要几次n&n-1,这是一个问题的转换过程,不必硬性计算32位的内容
代码实现:
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int ret = 0; while(0 != n){ n = n&(n-1); ++ret; } return ret; } }
相关文章推荐
- C++ 重载 覆盖 隐藏
- 在switch中的case语句中声明变量会被提前
- JavaScript:事件响应
- BZOJ3282Tree
- appium– Desired Capabilities详解
- 我还是不用百度免费的CDN好了!
- ppt怎么转换成pdf格式文件
- cuda 常量内存,头文件不知道有什么gui问题
- 自定义Toolbar左侧空白
- linux中fork()函数详解(原创!!实例讲解)
- 判断手机联网状态
- 查找两个有序数组的中位数和第K小的数
- openssl的Md5计算笔记
- Android中的设计模式--适配器模式
- 两个STM32之间进行SPI通信
- FC 交换机端口类型
- day04 面试题Schema约束与DTD约束的区别
- 怎么用eclipse修改web工程的访问路径
- 更新后的Xcode7.3
- C#解leetcode 152. Maximum Product Subarray