美文网首页
[LeetCode By Python] 190. Revers

[LeetCode By Python] 190. Revers

作者: 乐乐可爱睡觉 | 来源:发表于2016-06-15 14:09 被阅读206次

一、题目

Reverse Bits

二、解题

把一个无符号32的int,逆序输出。

如果把这一题当做二进制入门题,我觉得是很合适的,可惜最开始没有抽到这题,现在遇到这题就比较简单了。

  • 把n右移i位,对2求余,得到当前的位数
  • 把new 左移1位,或之前的值即可

三、尝试与结果

class Solution(object):
    def reverseBits(self, n):
        new = 0
        for i in range(32):
            new = (new << 1) | ((n >> i) % 2)
        return new

结果:AC

相关文章

网友评论

      本文标题:[LeetCode By Python] 190. Revers

      本文链接:https://www.haomeiwen.com/subject/zrqpdttx.html