LeetCode190——颠倒二进制位

我的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解题报告:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值