-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path190.py
More file actions
54 lines (45 loc) · 1.97 KB
/
190.py
File metadata and controls
54 lines (45 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/9/5 23:02
# @Author : Fhh
# @File : 190.py
# @Software: PyCharm
# good good study,day day up!
"""
颠倒给定的 32 位无符号整数的二进制位。
示例 1:
输入: 00000010100101000001111010011100
输出: 00111001011110000010100101000000
解释: 输入的二进制串 00000010100101000001111010011100 表示无符号整数 43261596,
因此返回 964176192,其二进制表示形式为 00111001011110000010100101000000。
示例 2:
输入:11111111111111111111111111111101
输出:10111111111111111111111111111111
解释:输入的二进制串 11111111111111111111111111111101 表示无符号整数 4294967293,
因此返回 3221225471 其二进制表示形式为 10111111111111111111111111111111 。
提示:
请注意,在某些语言(如 Java)中,没有无符号整数类型。在这种情况下,输入和输出都将被指定为有符号整数类型,并且不应影响您的实现,因为无论整数是有符号的还是无符号的,其内部的二进制表示形式都是相同的。
在 Java 中,编译器使用二进制补码记法来表示有符号整数。因此,在上面的 示例 2 中,输入表示有符号整数 -3,输出表示有符号整数 -1073741825。
进阶:
如果多次调用这个函数,你将如何优化你的算法?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-bits
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
class Solution:
def reverseBits(self, n: int) :
s = str(bin(n))[2:]
print(s)
s = '0' * (32 - len(s)) + s
print(s)
s = s[::-1]
res = 0
idx = 1
while idx <= 32:
res += int(s[-idx]) * 2 ** (idx - 1)
idx += 1
return res
if __name__ == '__main__':
s = Solution()
print(s.reverseBits(0b00000010100101000001111010011100))
# print(str(bin(10)))