LeetCode(190) Reverse Bits
2015-11-02 20:54
411 查看
题目
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?
Related problem: Reverse Integer
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
分析
题目要求将一个32位无符号整数对应的二进制串反转,求翻转后的二进制串对应的新的32位无符号整数值。也就是说,只要我们求得该输入无符号整数的二进制表示形式,将其反转,再转换为十进制即可。
注意的问题,题目明确要求了32位,也就是说对于整数的二进制串必然长度为32,若长度不足则用0补齐。处理后再反转,求新的十进制。
另外,对于此题,我们还需要想到用位运算处理来提高运算速度。
AC代码
class Solution { public: //方法一 uint32_t reverseBits(uint32_t n) { vector<int> bits; //利用位运算求二进制序列 while (n) { bits.push_back(n & 1); n = n>> 1; } //求二进制位反转后对应的十进制数,若bits中长度不足32,以0步之 uint32_t ret = 0; int size = bits.size(); for (int i = 0 ; i <size; ++i) { ret = ret + bits[i] * (1 << (32 - i - 1)); }//for return ret; } //简洁的解法2 uint32_t reverseBits2(uint32_t n) { uint32_t res = 0; for (int i = 0; i < 32; ++i) { res |= (((n >> i) & 1) << (31 - i)); } return res; } };
GitHub测试程序源码
相关文章推荐
- eclipse 安装egit 成功后Team中没有显示
- Socket原理与编程基础
- SHELL脚本基础
- 《leetCode》:Remove Nth Node From End of List
- Linux磁盘挂载与卸载
- libcef学习最详细的入门资料系列之二 :libcef的编译和运行,以及MFC下的实现
- 遇见gtest--事件
- Struts2返回JSON对象的方法总结
- 在spring的init-method指定的方法之前做一些事情要用BeanPostProcessor
- POI根据XML模版读取Excel
- java面试题总结
- java char基本数据类型
- 关于SQL Server 2014的数据库连接问题
- 事务四大特征:原子性,一致性,隔离性和持久性(ACID)
- win7系统IE浏览器重置的操作方法
- Mysql
- zf-删除重复数据只保留一条(转)
- C/C++中的内存补齐机制(2)
- Objective-C中的Protocol
- 阶乘之和