leetcode笔记:Number of 1 Bits
来源:互联网 发布:手机数字键盘钢琴软件 编辑:程序博客网 时间:2024/05/24 03:28
一. 题目描述
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'
。
容易想到,无论输入的是整数还是负数还是0,都可以将该整数和1进行位与操作。因此,定义一个sum
用于计算'1'
的个数,如果结果不为0,则表示该整数的最低位是1,++sum
。
然后,将1左移一位,再次与该整数进行与操作,如果结果不为0,说明整数的次低位为1,依次类推,当1移位到变为0时,统计结束。这种方法需要将1左移31位,也就是必须要循环32次。
改进一:
不对1进行左移操作,改为每次循环中对n进行右移操作,即:n = n >> 1,这样当n减少为0时可以跳出循环,不一定要循环32次。但对于:10000000000000000000000000000001
这样的数,也需要循环32次。
改进二:
这里需要举一个例子:
n = 0x110100 n-1 = 0x110011 n&(n - 1) = 0x110000 n = 0x110000 n-1 = 0x101111 n&(n - 1) = 0x100000 n = 0x100000 n-1 = 0x011111 n&(n - 1) = 0x0
因此,可以发现一种方法,对于含有sum个'1'
的整数n,只需循环sum次即可得出结果。以下给出了改进一和改进二的两种代码实现。
三. 示例代码
class Solution {public: int hammingWeight(uint32_t n) { int sum = 0; while (n > 0) { sum += n & 1; n = n >> 1; } return sum; }};// 效率较高class Solution {public: int hammingWeight(uint32_t n) { int sum = 0; while (n != 0) { n = n & (n - 1); ++sum; } return sum; }};
四. 小结
该题难度较低,但是也能挖掘出多种做法。在完成位运算的题目时,需要多加思考。
- leetcode笔记:Number of 1 Bits
- LeetCode笔记:191. Number of 1 Bits
- leetcode:bits:Number of 1 Bits(191)
- LeetCode:Number of 1 Bits
- LeetCode-Number of 1 Bits
- leetcode: Number of 1 Bits
- LeetCode Number of 1 Bits
- Leetcode: Number of 1 Bits
- Leetcode--Number of 1 Bits
- [LeetCode] Number of 1 Bits
- [leetcode]Number of 1 Bits
- Leetcode-Number of 1 Bits
- LeetCode Number of 1 Bits
- LeetCode-Number of 1 Bits
- [Leetcode] Number of 1 Bits
- [Leetcode]Number of 1 Bits
- leetcode--Number of 1 Bits
- leetcode:Number of 1 Bits
- AOJ 2249 图论之最短路
- Convert Sorted List to Binary Search Tree
- Android 把XML定义的控件动态实例化
- php如何处理这样的数据?
- iOS 第三方支付 支付宝支付
- leetcode笔记:Number of 1 Bits
- JS私有变量和静态私有变量
- leetcode——219—— Contains Duplicate II
- 查找轮廓总结
- ofstream和ifstream详细用法
- JAVA struts2框架下zip打包文件下载
- 【Android Framework】 Android Binder 机制解析
- Ubuntu使用caore dump定位程序错误
- Java maven 环境下使用proguard-maven-plugin 插件混淆代码