leetcode 190.颠倒二进制位

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

示例:

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

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

思路一:将数 n 与 1 进行 & 运算,得到末尾的数字,并且存入数组中,进行 32 次。然后将数组中的数字换成 十进制,这里要注意的是可能会溢出,要使用 long ,最后强制转型为 int。

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int i = 0;
        int[] result = new int[32];
        int j = 31;
        long sum = 0;
        while(i < 32){
            result[j--] = (n&1);
            n = n>>1;
            i++;
        }
        for(int k = 31;k >= 0;k--){
            sum += result[k] * Math.pow(2,k);
        }
        return (int)sum;
    }
}

思路二:不使用另外的数组存储每一次的结果,使用 r 即可。用 n & 1 得到 数 n 的末尾数字,然后将他与 r 进行或运算,最后将 r 右移 32 - i 位即可。>> 有符号数右移,>>> 无符号数右移。

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
		int r = 0;
        int i = 0;
        while(n != 0) {
            r = r << 1;
            r = r | (n & 1);
            n = n >>> 1;
            ++i;
        }
        return r << (32 - i);
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_40904220/article/details/83105207