PS/LeetCode
[LeetCode] 190. Reverse Bits
판교토끼
2020. 12. 8. 23:29
728x90
leetcode.com/problems/reverse-bits/
Reverse Bits - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
32비트로 고정된 길이의 input을 받아 뒤집어 10진수로 변환하는 문제이다. 파이썬의 내장 함수인 bin()를 사용하면, 이진수로 바꿀 수 있다. 예를들어 4는 0b100 으로 변환된다. 앞에 0b가 붙는 것과, 32비트로 고정된 길이지만 앞의 padding용 0은 지워진다는 점을 이용해, 변환 후 앞 2문자를 제거하고 길이가 32가 될 때까지 0을 붙였다.
이는 string 형태이기 때문에 다시 2진수로 바꾸고, int로 바꾸어준다.
class Solution:
def reverseBits(self, n: int) -> int:
bin_n = bin(n)[2:]
while len(bin_n) < 32:
bin_n = '0'+bin_n
return int('0b' + bin_n[::-1], 2)
728x90