[LeetCode]Reverse Bits

Question

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

Follow up:
If this function is called many times, how would you optimize it?


本题难度Easy。有2种算法分别是: 位运算 和 分段调换法

1、位运算

复杂度

时间 O(N) 空间 O(1)

思路

取出n的最低位b,将ans左移后将b赋给ans的最低位,然后将n右移。

注意

第8行我开始写成ans=ans<<1+(n&1);,这样得到的结果是错误的,原因就在于<<优先级低于+,实际上它相当于ans=ans<<(1+(n&1));,正确的写法应该是ans=(ans<<1)+(n&1);

代码

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        //require
        int ans=0;
        //invariant
        for(int i=0;i<32;i++){
           ans=ans<<1|(n&1);
           n>>=1;
        }
        //ensure
        return ans;
    }
}

2、分段调换法

复杂度

时间 O(N) 空间 O(1)

思路

试想一下,我们还有没有更好的方案呢,答案当时是肯定的。在斯坦福的这篇文章(http://graphics.stanford.edu/~seander/bithacks.html)里面介绍了众多有关位操作的奇思妙想,有些方法的确让人称赞,其中对于位翻转有这样的一种方法,将数字的位按照整块整块的翻转,例如32位分成两块16位的数字,16位分成两个8位进行翻转,这样以此类推知道只有一位。

例如对于一个8位数字abcdefgh来讲,处理的过程如下:

abcdefgh -> efghabcd -> ghefcdab -> hgfedcba

注意

这里的n是有符号数,因此右移要使用无符号右移>>>而不可用>>

代码

public class Solution {
    // you need treat n as an unsigned value
    public int reverseBits(int n) {
        //invariant
        n = (n >>> 16) | (n << 16);
        n = ((n & 0xff00ff00) >>> 8) | ((n & 0x00ff00ff) << 8);
        n = ((n & 0xf0f0f0f0) >>> 4) | ((n & 0x0f0f0f0f) << 4);
        n = ((n & 0xcccccccc) >>> 2) | ((n & 0x33333333) << 2);
        n = ((n & 0xaaaaaaaa) >>> 1) | ((n & 0x55555555) << 1);
        //ensure
        return n;
    }
}

Follow up

Q:如果该方法被大量调用,或者用于处理超大数据(Bulk data)时有什么优化方法?
A:这其实才是这道题的精髓,考察的大规模数据时算法最基本的优化方法。其实道理很简单,反复要用到的东西记下来就行了,所以我们用Map记录之前反转过的数字和结果。更好的优化方法是将其按照Byte分成4段存储,节省空间。参见这个帖子

代码

public class Solution {
    // cache
    private final Map<Byte, Integer> cache = new HashMap<Byte, Integer>();
    public int reverseBits(int n) {
        byte[] bytes = new byte[4];
        for (int i = 0; i < 4; i++) // convert int into 4 bytes
            bytes[i] = (byte)((n >>> 8*i) & 0xFF);
        int result = 0;
        for (int i = 0; i < 4; i++) {
            result <<= 8;
            result += reverseByte(bytes[i]); // reverse per byte
        }
        return result;
    }

    private int reverseByte(byte b) {
        Integer value = cache.get(b); // first look up from cache
        if (value != null)
            return value;
        value = 0;
        // reverse by bit
        for (int i = 0; i < 8; i++) {
            value <<= 1;
            value += ((b >>> i) & 1);
        }
        cache.put(b, value);
        return value;
    }
}

参考

[Leetcode] Reverse Bits 反转位

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值