【LeetCode刷题记录】Reverse Bits
2015-05-06 22:02
211 查看
题目
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位无符号整数按照二进制位逆序排列,得到一个新的数。最开始的思路是首先得到十进制数的32位二进制数的数组(可通过掩码方式取得每一位),然后对数组进行前后交换,最后将十进制数还原。虽然步骤较多,但可以AC,代码如下:[code]uint32_t reverseBits(uint32_t n) { // Solution 1 int a[32], temp, mask = 0x1, result = 0; for (int i=0; i<32; i++) { a[i] = (n & (mask<<i)) >> i; for (int j=0; j<16; j++) { temp = a[j]; a[j] = a[31-j]; a[31-j] = temp; } for (int k=0; k<32; k++) { result += (a[k]<<k); return (uint32_t)result; }
上述方法需要申请一个32个元素大小的数组保存每一位,进行了三次循环,略显繁琐。能不能不使用中间数组呢?答案当然是能。逆序实际上是使低位最终到高位上,如果从最低位开始处理,然后每一次处理完,将最低位往高位移动一位。那么,当处理完最高位时,最低位自然就到了最高位的位置。话不多说,AC代码如下:
[code]uint32_t reverseBits(uint32_t n) { // Solution 2 uint32_t result = 0; for (int i=0; i<32; i++) {// from the lowest bit result = result << 1;// move the low bit to high position result = result | (n & 1); n = n >> 1;// get the next high bit } return result; }
思考:本质上对二进制位的操作多数情况下是结合掩码和位运算(与、或、非和异或操作),这一点在《深入理解计算机系统》一书的第二章讲解得十分透彻。推荐阅读!:-)
相关文章推荐
- [LeetCode刷题记录]190-191 Number of 1 Bits & Reverse Bits
- LeetCode记录之——Generate Parentheses
- 个人记录-LeetCode 107. Binary Tree Level Order Traversal II
- Leetcode-190 Reverse Bits
- LeetCode(190) Reverse Bits
- leetcode刷题,总结,记录,备忘26
- 个人记录-LeetCode 24. Swap Nodes in Pairs
- leetcode 732. My Calendar III 我的日历 + 统计最大公共区间+ 使用Map记录出入度
- leetcode刷题,总结,记录,备忘 199
- Leetcode习题记录——Longest Common Prefix
- 【LeetCode题目记录-4】插入数组间隔问题
- leetcode刷题,总结,记录,备忘 309
- leetcode刷题,总结,记录,备忘300
- 【LeetCode题目记录-12】所有合法的括号序列
- leetcode刷题,总结,记录,备忘 226
- leetcode 记录 349. Intersection of Two Arrays
- leetcode刷题记录-35. Search Insert Position
- leetcode刷题记录——349.intersection of two arrays
- [LeetCode刷题记录]Single Number II
- 【Leetcode解题记录】12. Integer to Roman