题目链接:https://leetcode.com/problems/reverse-bits/
题目:
Reverse bits of a given 32 bits unsigned integer.
00000010100101000001111010011100), return 964176192 (represented in binary as00111001011110000010100101000000).
Follow up:
If this function is called many times, how would you optimize it?
思路:
n和它要交换位的掩码(如010000010)异或结果就是交换后的结果。先判断要交换位如果不相等,用异或交换。
算法:
1. public int reverseBits(int n) {
2. for (int i = 0; i < 16; i++) {
3. int bi = (n >> i) & 1;
4. int bj = (n >> (32 - i - 1)) & 1; // 取要交换的两个bit值
5. if ((bi ^ bj) != 0) {// 如果两bit不同
6. // n和 它要交换的位置为1其余位置为0的数异或的结果 就是n交换的结果
7. // (1<<i)|(1<<(32-i-1)) 得到的就是要交换位为1,其余位为0的类似于掩码一样的值如 1000001
8. 1 << i) | (1 << (32 - i - 1));
9. }
10. }
11. return n;
12. }