LeetCode190——颠倒二进制位

版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/86590251

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/reverse-bits/description/

题目描述:

知识点:位运算

思路一:先将十进制转换成二进制,再颠倒二进制字符串,最后输出十进制数

注意,将颠倒后的二进制字符串转换为十进制时,不能直接调用Integer.parseInt()函数。因为该函数不会将二进制字符串当作补码处理,当然对于正数我们可以直接调用该函数

对于负数,我们需要将字符串的每一位都取反,再调用Integer.parseInt()函数,将所得结果取负数再减一

JAVA代码:

public class Solution {
    public int reverseBits(int n) {
        StringBuilder stringBuilder = new StringBuilder(Integer.toBinaryString(n)).reverse();
        while(stringBuilder.length() < 32){
            stringBuilder.append("0");
        }
        if('0' == stringBuilder.charAt(0)) {
            return Integer.parseInt(stringBuilder.toString(), 2);
        }
        for (int i = 0; i < stringBuilder.length(); i++) {
            if('0' == stringBuilder.charAt(i)){
                stringBuilder.setCharAt(i, '1');
            }else{
                stringBuilder.setCharAt(i, '0');
            }
        }
        return -1 - Integer.parseInt(stringBuilder.toString(), 2);
    }
}

LeetCode解题报告:

思路二:用位运算反转二进制数

JAVA代码:

public class Solution {
    public int reverseBits(int n) {
        int result = 0;
        for (int i = 0; i < 32; i++) {
            result += n & 1;
            n >>= 1;
            if(i != 31){
                result <<= 1;
            }
        }
        return result;
    }
}

LeetCode解题报告:

思路三:将32位进制数拆分成4个byte类型的数,用哈希表记录每个byte数翻转后的十进制数结果

这个思路其实是记忆化搜索,有动态规划的影子。虽然从LeetCode解题报告来看此思路花费时间比思路一和思路二都要高,但还是在一个级别的,同时对于多次调用有优势。

JAVA代码:

public class Solution {
    private HashMap<Byte, Integer> hashMap = new HashMap<>();
    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 += reverseByte(bytes[i]);
            if(i != 3){
                result <<= 8;
            }
        }
        return result;
    }
    private int reverseByte(byte n){
        Integer result = hashMap.get(n);
        if(null != result){
            return result;
        }
        result = 0;
        for (int i = 0; i < 8; i++) {
            result += (n >> i) & 1;
            if(i != 7){
                result <<= 1;
            }
        }
        hashMap.put(n, result);
        return result;
    }
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/86590251