190. Reverse Bits

一、题目

  1、审题

  

  2、分析

    给出一个 32位的无符号整形,将其二进制形式进行翻转,求出反转后的二进制代表的数值。

二、解答

  1、思路:

    方法一、

      采用位运算符进行运算。

      ①、n & 1 可以取到 n 的最后一位二进制位 end;

      ②、n >>>= 1,n 无符号右移一位

      ③、result <<= 1, result |= end; result 左移一位,且将 end 添加在 result 尾部。

    public int reverseBits(int n) {
        int result = 0;
        for(int i = 0; i < 32; i++) {
            int end = n & 1; // 计算 n 的最后一位
            n >>>= 1;        // n 无符号右移一位
            result <<= 1;    // result 左移一位
            result |= end;   // result 添加 n 的末尾一位
        }
        return result;
    }

  优化:

     当此方法需要被多次调用时,可以将 n 分成 4 份 8 bit ;

   且将用到的 8bit 二进制的翻转存入到一个 Map 作为 cache。

    public int reverseBits(int n) {
        byte[] bytes = new byte[4];
        for (int i = 0; i < 4; i++) 
            bytes[i] = (byte)((n >>> 8*i) & 0xFF);
        
        int result = 0;
        for(int i = 0; i < 4; i++) {
            result <<= 8;
            result += reverseByte(bytes[i]);
        }
        return result;
    }
    
    private int reverseByte(byte b) {
        Integer value = cache.get(b);
        if(value != null)
            return value;
        
        value = 0;
        for(int i = 0 ; i < 8; i++) {
            value <<= 1;
            value += ((b >>> i) & 1);
        }
        cache.put(b, value);
        return value;
    }
原文地址:https://www.cnblogs.com/skillking/p/9806654.html