leetcode-reverse-bits

题目大意

  https://leetcode.com/problems/reverse-bits/

  给你一个整数,视其为unsigned int,按位reverse这个数

题目分析

  位运算,但是题目中提到,如果这个方法多次调用,如何进行效率上的优化(提交以后你会发现test case会有600组)参考https://discuss.leetcode.com/topic/9863/my-3ms-pure-c-solution/2 解法,以4位为一组,一共8组,每4位可能的翻转情况就16种,提前存在数组中。

代码

  正常的按位计算代码

1
2
3
4
5
6
7
8
9
10
11
12
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int ans = 0;
for (int i = 0; i <= 31; i++) {
ans <<= 1;
ans |= (n & 1);
n >>= 1;
}
return ans;
}
}

  4位一组附加存储的优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Solution {
// you need treat n as an unsigned value
private static char[] reverse = new char[]{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15};
public int reverseBits(int n) {
int ans = 0;
for (int i = 0; i < 8; i++) {
ans <<= 4;
ans |= reverse[n & 0xF];
n >>= 4;
}
return ans;
}
}