[leetcode-190]Reverse Bits(C)
2015-08-27 08:40
344 查看
问题描述:
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?
分析:这道题主要考察对bit位的操作。这里使用两个指针,从两端向中间逼近,每次交换对应项位置。
代码如下:4ms
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?
分析:这道题主要考察对bit位的操作。这里使用两个指针,从两端向中间逼近,每次交换对应项位置。
代码如下:4ms
[code]uint32_t reverseBits(uint32_t n) { uint32_t slow = 1 << 0, fast = 1 << 31; while (fast>slow) { //swap uint32_t slowVal = slow & n; uint32_t fastVal = fast & n; if (slowVal) { n |= fast; } else { n &= ~fast; } if (fastVal) { n |= slow; } else { n &= ~slow; } fast = fast >> 1; slow = slow << 1; } return n; }
相关文章推荐
- HDU 2955 Robberies
- C# 创建多级文件夹示例
- GUI编程笔记11:使用Netbeans工具进行GUI编程
- 微软推《蹦词打词》应用以及下载地址:练习Win10 Mobile中文滑行输入
- 文章标题
- 黑马程序员——java基础 多线程(复习)
- jquery+php随机生成红包金额数量代码分享
- php给图片添加文字水印方法汇总
- c#通过webrequest请求远程http服务时出现的问题
- java 中记录时间
- 微软官方Win10快捷键文档(英文版)下载 可打印版
- 访问项目搁置一段时间再访问的时候,就出现了如上的异常;
- android 赋值或点击事件混乱
- PullScrollView详解(四)——完全使用listview实现下拉回弹(方法一)
- VMware Server中虚拟机随宿主机自动启动
- itext生成PDF文件报错“Font 'STSong-Light' with 'UniGB-UCS2-H' is not recognized.”
- 【POJ2594】Treasure Exploration 宝藏勘探
- iOS UI21_多线程
- Android EditText中的inputType
- java-集合 各个类之间继承关系图