[leetcode190]Reverse Bits

问题描述:

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?

Related problem: Reverse Integer

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

算法:

先计算出n的二进制表示,由于涉及到2的0-31次幂,所以使用列表表示n的二进制,其index与位数正好对应,两次扫描解决。
rest = n
第一次从index=31处开始,逐次得到每个位置的值,array[index] = rest/2**index,
rest -= array[index]*2**index。
第二次从index=0处开始,累加每个位置的值array[index]*2**(31-index).
最后累加和就是结果。

代码:

class Solution(object):
    def reverseBits(self, n):
        """
        :type n: int
        :rtype: int
        """
        array = [0 for _ in range(32)]
        rest = n
        for index in range(31,-1,-1):
            array[index] = rest/2**index
            rest -= array[index]*2**index

        s = 0
        for idx, value in enumerate(array):
            s += value*2**(31-idx)
        return s
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值