• leetcode——190.颠倒二进制位


    将十进制数转换为二进制数:
    使用bin()函数即可

    二进制转十进制用int函数:

            b=a[::-1]
            print(b)
            c=int(b,2)

    但是操作的时候却遇到了错误:ValueError: invalid literal for int() with base 2: '1101111b0'

    解决办法:

    仔细看是因为十进制转换为二进制的时候,会有一个前缀为0b,所以在将图转换为十进制的时候,需要将这两个去掉才能进行。

    执行结果错了一次,因为要求是32位进行转换,但是我直接转了,没有考虑到补零的问题:


    class
    Solution: # @param n, an integer # @return an integer def reverseBits(self, n): a=bin(n) b=a[:1:-1] d=b+'0'*(32-len(b)) return int(d,2)
    执行用时 :20 ms, 在所有 Python 提交中击败了86.90%的用户
    内存消耗 :11.9 MB, 在所有 Python 提交中击败了5.34%的用户
     
    
    
    执行用时为 8 ms 的范例
    class Solution:
        # @param n, an integer
        # @return an integer
        def reverseBits(self, n):
            return int(('%032d'%int(bin(n)[2:]))[::-1],2)

    没太看懂。。。。。差距啊差距。。。。。。

    执行用时为 16 ms 的范例
    class Solution:
        # @param n, an integer
        # @return an integer
        def reverseBits(self, n):
            return int(bin(n)[2:].zfill(32)[::-1],2)
    zfill(32)

    神奇啊!!!

                                                                          ——2019.10.10

    我的前方是万里征途,星辰大海!!
  • 相关阅读:
    CodeForces 7B
    CodeForces 4D
    离散化
    线段树入门
    洛谷 P3951 小凯的疑惑(赛瓦维斯特定理)
    Codeforces 1295D Same GCDs (欧拉函数)
    Codeforces 1295C Obtain The String (二分)
    Codeforces 1295B Infinite Prefixes
    Codeforces 1295A Display The Number(思维)
    Codeforces 1294F Three Paths on a Tree(树的直径,思维)
  • 原文地址:https://www.cnblogs.com/taoyuxin/p/11649238.html
Copyright © 2020-2023  润新知