190. Reverse Bits [easy] (Python)
2016-06-18 11:04
591 查看
题目链接
https://leetcode.com/problems/reverse-bits/题目原文
Reverse bits of a given 32 bits unsigned integer.For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
题目翻译
翻转一个给定的32位无符号数的位。比如,给定输入整数43261596(二进制表示为00000010100101000001111010011100),返回964176192(二进制表示为00111001011110000010100101000000)。进一步:如果该函数被多次调用,你该如何优化它?
思路方法
思路一
先将输入转换成2进制字符串,再翻转并扩充到32位,再将此32位的二进制转为无符号整数即可。利用Python的bin()函数很方便。代码
class Solution(object): def reverseBits(self, n): """ :type n: int :rtype: int """ b = bin(n)[:1:-1] return int(b + '0'*(32-len(b)), 2)
思路二
按位处理,将输入n的二进制表示从低位到高位的值依次取出,逆序排列得到翻转后的值。这里更新res的时候,用纯位操作会比用加法要快的多。代码
class Solution(object): def reverseBits(self, n): """ :type n: int :rtype: int """ res = 0 for i in xrange(32): res <<= 1 res |= ((n >> i) & 1) return res
思路三
还有一种看起来比较暴力,其实也比较巧妙的方法。类似二分的思想,每次处理一半的位交换,具体看代码吧。代码
class Solution(object): def reverseBits(self, n): """ :type n: int :rtype: int """ n = (n >> 16) | (n << 16); n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8); n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4); n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2); n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1); return n
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:/article/11857869.html
相关文章推荐
- Python爬虫学习系列教程
- Python包的编写和使用
- Python day01周
- Python模块的编写和调用
- VII Python(5)基础知识(模块、包、异常)
- python学习笔记9-函数递归调用
- 【p1】·python的下载与安装(pigeon详细说)
- 编译原理-词法分析-语法分析-语义分析生成中间代码-python版
- python反射
- 一行 Python 实现并行化 — 日常多线程操作的新思路
- Python-开发之路-递归&反射
- python 学习笔记 copy
- Python的特殊属性和用法
- Python-开发之路-模块
- python学习笔记8-函数的多类型传值和冗余参数
- Python学习8
- python 学习笔记 基础
- 【翻译】Tweepy 3.5.0 Doc (3) Code Snippets
- python练习-工资计算器
- python中的map、filter、reduce函数