【做题也是一场游戏】190. 颠倒二进制位

184 阅读1分钟

题目地址

leetcode-cn.com/problems/re…

题目描述

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

提示:

请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。 在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 2 中,输入表示有符号整数 -3,输出表示有符号整数 -1073741825。

题解

两两交换

直接将高位和对应低位进行交换

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        int low = 0;
        int high = 0;
        int result = 0;
        for (int i = 0; i < 16; i++) {
            low = n & (1 << i);
            high = n & (1 << (32 - i -1));
            result = result | (low << (32 - i - 1 - i));
            result = result | (high >>> (32 - i - 1 - i));
        }
        return result;
    }
}

复杂度分析

  • 时间复杂度:O(logn)O(\log n), nnInteger.SIZE

  • 空间复杂度:O(1)O(1)

分治法

先对半分,进行交换,在将每个半分进行半分进行交换,直到能交换的只有一位

jdk 也是这种实现

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        n = ((n & 0x0000ffff) << 16 ) | ((n & 0xffff0000) >>> 16);
        n = ((n & 0x00ff00ff) << 8 ) | ((n & 0xff00ff00) >>> 8 );
        n = ((n & 0x0f0f0f0f) << 4 ) | ((n & 0xf0f0f0f0) >>> 4 );
        n = ((n & 0x33333333) << 2 ) | ((n & 0xCCCCCCCC) >>> 2 );
        n = ((n & 0x55555555) << 1 ) | ((n & 0xAAAAAAAA) >>> 1 );

        return n;
    }
}

复杂度分析

  • 时间复杂度:O(1)O(1)

  • 空间复杂度:O(1)O(1)