• LeetCode:190. 颠倒二进制位


    1、题目描述

    颠倒给定的 32 位无符号整数的二进制位。

    示例:

    输入: 43261596
    输出: 964176192
    解释: 43261596 的二进制表示形式为 00000010100101000001111010011100 ,
         返回 964176192,其二进制表示形式为 00111001011110000010100101000000 。
    

    进阶:
    如果多次调用这个函数,你将如何优化你的算法?

    2、题解

    2.1、解法一

    class Solution:
        # @param n, an integer
        # @return an integer
        def reverseBits(self, n):
            ret = bin(n)[2:]
            ret = reversed(ret)
            l = list(ret)
            l.extend(['0' for i in range(32-len(l))])
            s = "".join(l)
            return int(s,2)
    

    2.2、解法二

    class Solution:
        # @param n, an integer
        # @return an integer
        def reverseBits(self, n):
            ret = bin(n)[2:]
            ret = "".join(['0' for i in range(32-len(ret))]) +ret
            new = reversed(ret)
            print(new)
            return int("".join(list(new)),2)
    

      

  • 相关阅读:
    第八章 多线程编程
    Linked List Cycle II
    Swap Nodes in Pairs
    Container With Most Water
    Best Time to Buy and Sell Stock III
    Best Time to Buy and Sell Stock II
    Linked List Cycle
    4Sum
    3Sum
    Integer to Roman
  • 原文地址:https://www.cnblogs.com/bad-robot/p/10065648.html
Copyright © 2020-2023  润新知