[LeetCode] #190 Reverse Bits

Fatboy Slim
1 min readMar 13, 2020

--

Environment: Python 3.7

Key technique: format, slice,reverse[::-1]

Example 1:

Input: 00000010100101000001111010011100
Output: 00111001011110000010100101000000
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.

Example 2:

Input: 11111111111111111111111111111101
Output: 10111111111111111111111111111111
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.

Analysis:

Convert int into 32 bit and reverse it. Convert 32 bit into int.

Solution:

class Solution:
def reverseBits(self, n: int) -> int:
a= '{0:032b}'.format(n)
reverse = a[::-1]
return int(reverse,2)

Submitted result:

Lesson learn:

Learn format transformation.

Reference:

https://leetcode.com/problems/reverse-bits/discuss/520782/easy_python_faster_solution

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet