letcode 颠倒二进制位

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

示例:

输入: 43261596
输出: 964176192
解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 ,
返回 964176192,其二进制表示形式为 00111001011110000010100101000000 。
进阶:
如果多次调用这个函数,你将如何优化你的算法?
想了半天没想到解决方法,然后看一位大佬的思路,先获取n的最后一位给result,然后n右移一位,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&ox01;
            n>>1;
            result = (result<<1) | temp;
            i++;
        }
        return result;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37520037/article/details/82320973