LeetCode190. 颠倒二进制位

题目

颠倒给定的 32 位无符号整数的二进制位。

示例:

输入: 43261596
输出: 964176192
解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 ,
     返回 964176192,其二进制表示形式为 00111001011110000010100101000000 

进阶:
如果多次调用这个函数,你将如何优化你的算法?

 分析

把某个二进制数字颠倒一下,那我们可以从后向前的取这个二进制数字的每一位数,同时从前到后的重新赋值给我们的结果。

与运算在两个数字都为1的时候才是1,我们可以让00000010100101000001111010011100这一大串数字依次和 1 做与运算,如果结果为0, 那么当前位就是0,结果是1 当前位是1;做完与运算还要将数字向右位移一位,结果向左位移一位,同时还要加上当前位,如果是1则加1,是0就不加。

代码

下面的代码是我在提交之后发现的时间最快的,它把我用的+1换成了或运算,这样会更快些。

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int result = 0;
        for (int i = 0; i < 32; i++) {
            if ( (n & 1) == 1)
                result = (result << 1) + 1 ;
            else
                result = (result << 1);
            n = n >> 1;
        }
        return result;
    }
}
public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int result = 0;
        int i = 0;
        while (i < 32) {
            int temp = n & 1;
            n = n >> 1;

            result = (result << 1) | temp;
            i++;
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_38595487/article/details/83474682