Leetcode#190. Reverse Bits (反向位&位运算)

声明:题目解法使用c++和Python两种,重点侧重在于解题思路和如何将c++代码转换为python代码。

题目

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?

题意

给你一个32位无符号整数,求出它的反向位(即二进制的逆序得到的整数)

思路

主要注意的点:必须是32位
例如2的二进制为 10
逆序为:01 = 1
要是这么理解你就错了,仔细看题意,正确的结果要的是:01000000000000000000000000000000
2的31次方(不要以为超出int范围,题意说了是无符号)。
博主的思路是先求出逆序保存在数组中,然后不满32位,补0。

解法一: C++版

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {

        int res = 0;
        int a[32] = {0},k = 0;

        while(n)
        {
            a[k++] = n % 2;
            n /= 2;//除以2
        }

        for (int i=0;i<32;i++)
            res = res * 2 + a[i];
        return res;
    }
};

运行时间:
这里写图片描述

但是,题意还说:
If this function is called many times, how would you optimize it?
如果这个函数被多次调用,如何优化它?
博主首先想到了是位运算,修改后的代码:

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {

        uint32_t res = 0;
        int a[32] = {0},k = 0;

        while(n)
        {
            a[k++] = n % 2;
            n = n >> 1;//除以2
        }

        //注意 <<的运算级小于 + 的运算级
        for (int i=0;i<32;i++)
            res = (res << 1) + a[i];
        return res;
    }
};

运行时间:
这里写图片描述
果然时间缩短了一半。
下面是博主在九章算术看到了特别简洁的代码,原代码是java版的,下面是改成了c++版。

class Solution {
public:
    uint32_t reverseBits(uint32_t n) {

        uint32_t res = 0;
        for (int i=0;i<32;i++)
        {
            res = (res << 1) | (n & 1);
            n = (n >> 1);
        }
        return res;
    }
};
  • n&1 : n和1做“按位与”运算,1的二进制只有末位是1,所以n&1就是只保留n的末位(二进制)。同时n&1就表示了n的奇偶性。
  • | : 如果存在于任一操作数中,二进制 OR 运算符复制一位到结果中。
    例如:
    假设如果 A = 60,且 B = 13,现在以二进制格式表示,它们如下所示:
A = 0011 1100
B = 0000 1101
(A | B) 将得到 61,即为 0011 1101

运行时间:这里写图片描述

解法二: Python版

class Solution:
    # @param n, an integer
    # @return an integer
    def reverseBits(self, n):

        res = 0
        for i in range(0,32):
            res = (res << 1) | (n & 1)
            n = (n >> 1)
        return res

运行时间:
这里写图片描述

GitHub本题题解:https://github.com/xuna123/LeetCode/blob/master/Leetcode%23190.%20Reverse%20Bits%20.md

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值