LeetCode 190. Reverse Bits(翻转比特)
2016-05-04 02:49
330 查看
原题网址: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 as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
方法一:直接操作。
方法二:参考:https://leetcode.com/discuss/27405/o-1-bit-operation-c-solution-8ms
Reverse bits of a given 32 bits unsigned integer.
For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
Related problem: Reverse Integer
方法一:直接操作。
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int reversed = 0; for(int i=0; i<32; i++) { reversed <<= 1; reversed |= n & 1; n >>= 1; } return reversed; } }
方法二:参考:https://leetcode.com/discuss/27405/o-1-bit-operation-c-solution-8ms
public class Solution { // you need treat n as an unsigned value public int reverseBits(int n) { int s = n >= 0 ? 0 : 1; n &= 0b01111111111111111111111111111111; long m = n; m = ((m & 0xffff0000) >> 16) | ((m & 0x0000ffff) << 16); m = ((m & 0xff00ff00) >> 8) | ((m & 0x00ff00ff) << 8); m = ((m & 0xf0f0f0f0) >> 4) | ((m & 0x0f0f0f0f) << 4); m = ((m & 0xcccccccc) >> 2) | ((m & 0x33333333) << 2); m = ((m & 0xaaaaaaaa) >> 1) | ((m & 0x55555555) << 1); m |= s; return (int)m; } }
相关文章推荐
- NAS
- http笔记
- 关系数据库常用SQL语句语法大全
- linux重定向及nohup不输出的方法
- 冒泡排序的例题讲解
- JDK中的设计模式
- cocos2d-lua+cocos studio之ListView加载Item
- [python]常见数据结构归纳
- 时光隽永,少年何惑
- Provisioning Services 7.8 入门系列教程之四 目标设备安装
- Provisioning Services 7.8 入门系列教程之四 目标设备安装
- Linux下ntpdate时间同步
- Android Studio 进阶详细配置
- 纹理--高清设计素材下载
- .NET平台开源项目速览-最快的对象映射组件Tiny Mapper之项目实践
- Unity3D UNET 模仿局域网游戏(一)
- linux下的时间及时区设置
- 数组实用类:Arrays
- Codeword codeforces 666c
- ROS玩AR.drone(-1-)