Grand 169 questions 第4周 第1题-190. 颠倒二进制位

第1题-190. 颠倒二进制位

暴力

很容易想到,我们可以计算出n的最低位,然后将其左移32 - i - 1位。

这样,就颠倒了n的最低位,依次顺序,知道n == 0即可。

public class Solution {
    public uint reverseBits(uint n) {
        uint ret = 0;
        for (int i = 0; i < 32 && n > 0; ++i) {
            ret |= (n & 1) << (31 - i);
            n >>= 1;
        }
        return ret;
    }
}

分治位运算

笑死,根本想不到,我是废物

190. 颠倒二进制位 - 力扣(Leetcode)

这个是源码级的算法。

public class Solution {
    private static uint M1 = 0x55555555; // 01010101010101010101010101010101
    private static uint M2 = 0x33333333; // 00110011001100110011001100110011
    private static uint M4 = 0x0f0f0f0f; // 00001111000011110000111100001111
    private static uint M8 = 0x00ff00ff; // 00000000111111110000000011111111

    public uint reverseBits(uint n) {
        n = n >> 1 & M1 | (n & M1) << 1;
        n = n >> 2 & M2 | (n & M2) << 2;
        n = n >> 4 & M4 | (n & M4) << 4;
        n = n >> 8 & M8 | (n & M8) << 8;
        return n >> 16 | n << 16;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值