Leetcode/Binary

[Leetcode 아주 상세한 문제풀이] 190. Reverse Bits - 코드 line 별 설명

PhD엔지니어 2023. 12. 26. 05:03

Leetcode 문제

이번에 풀어볼 문제는 리트코드 190번 문제 Reverse bits 이다.

우선 문제를 살펴보자.

 

리트코드 190번 문제 Reverse bits 

Reverse Bits - LeetCode

 

Reverse Bits - LeetCode

Can you solve this real interview question? Reverse Bits - Reverse bits of a given 32 bits unsigned integer. Note: * Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed

leetcode.com

 

 

Reverse bits of a given 32 bits unsigned integer.

Note:
Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.


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

Example 2:
Input: n = 11111111111111111111111111111101
Output:   3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
 
Constraints:
The input must be a binary string of length 32

 

 

문제 설명

문제는 매우 간단한다. 입력값으로 32 bits unsigned integer가 주어진다. 여기서 32 bits는 말 그대로 0 혹은 1이 32자리라는 것이고, unsigned라는 말은 부호 (+/- 등)가 없다는 뜻이다. 이때 주어진 32 bits unsigned integer를 거꾸로 출력하라는 것이다. 문제 예시에서는 32 bits여서 한번에 알아보기 조금 어렵다. 쉬운 예로 들면 11001이라는 값이 주어 졌을 때 뒤에서 부터 차례로 1 -> 0 -> 0 -> 1 -> 1 순서로 읽어 10011이라는 값을 출력하라는 문제다. 단, 출력은 32 bits 2진수로 하지말고 그에 상응하는 값인 10진수로 출력해야 한다. 곧바로 문제를 풀어보도록 하자.

 

 

문제 접근법

이 문제 풀이방법은 여러가지 일 수 있지만

우리는 파이썬을 이용하는 만큼 파이선 내장 함수를 이용하여 풀어보도록 하자.

이번 문제 풀이에 필요한 파이썬 내장 함수에 대해 간단히 알아보자.


1) bin () 함수

bin() 함수는 정수를 2진법으로 변환하는데 필요하다.

예를 들어 integer_n이 10인 경우를 생각해보자.

이때 bin (integer_n) 함수를 처리하면 아래 결과에서 보는 것처럼 2진수 표기로 변환된다.

여기서 '0b'는 이 값이 2진수임을 나타내는 파이썬의 prefix다.

따라서 '0b'를 제외한 값, 10을 2진수로 변환한 값  '1010'을 얻을 수 있다.

 

2) zfill() 함수

zfill 함수는 문자열 처리 함수 중 하나로 괄호 안 숫자 만큼 0을 채워 자리수를 맞춰준다.

아래 코드에 보는 것처럼 주어진 2진수가 1010이라고 생각해 보자.

이째 zfill(8) 함수를 이용하여 주어진 값 1010을 변환시켜 주면

괄호 안 숫자 만큼 8자리 수를 만들어줘야 하기 때문에,

자리수 맞추기를 위한 0을 추가해 아웃풋으로 00001010이 나오게 된다.

 

 

이제 문제 풀이에 필요한 파이썬 내장함수에 대해 알아봤으니 곧바로 문제를 풀어보도록 하자.

 

 

문제 풀이

우선 문제 풀이를 위한 class를 선언해준다. (line 1)

그리고 2진수로 표현되는 문자릉를 입력받기 위한 함수를 정의해 준다 (line 2)

입력된 값이 문자열이고 파이썬 내장함수는 숫자 처리를 해야하기 때문에

입력된 문자열을 2진수 integer로 '표현'해준다 (line 4)


(line 7, bin (integer_n))

앞서 설명한대로 우선 2진수로 '표현'된 integer를 bin()함수를 이용하여 2진수로 변환한다 (ine 7)

말 그대로 line 4는 주어진 문자열을 0과 1로 표현하기 위함이고,

실제 파이썬에서 2진수 처리를 위해서는 주어진 값을 '0b'로 시작하는 2진수로 변환해 줘야 한다.


(line 7, bin (integer_n)[2:])

그리고 변환된 2진수는 파이썬 정의대로 항상 '0b'가 앞에 prefix로 붙기 때문에

우리가 필요한 2진수는 '0b'를 제외한 두 번째 인덱스에 해당하는 값을 취한다.


(line 7, bin (integer_n)[2:].zfill(32))

'0b'를 제외한 뒤 취한 2진수 값을 32자리 수로 변환한다

앞서 설명한대로 zfill 함수를 이용하는데 (32) 값을 넣어줌으로써 32자리수를 만든다


(line 7, bin (integer_n)[2:].zfill(32)[::-1])

마지막으로 32자리수로 만들어진 2진수를 거꾸로 읽는다.

앞서 설명했듯 zfill는 문자열 처리 함수기 때문에,

거꾸로 읽은 후 이 수를 다시 0과 1로 표현되는 integer로 변환한다.

마지막으로 그 수를 리턴하며 종료한다. (line 9)

 

 

문제 풀이 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution:
    def reverseBits(self, n):
        # Convert the binary string to an integer
        integer_n = int(n, 2)
        print(integer_n)
        # Reverse the bits and convert back to an integer
        reversed_n = int(bin(integer_n)[2:].zfill(32)[::-1], 2)
        
        return reversed_n
 
# Example usage:
# Create an instance of the Solution class
solution = Solution()
 
# Example 1:
binary_str1 = "00000010100101000001111010011100"
result1 = solution.reverseBits(binary_str1)
print(result1)  # Output: 964176192
 
# Example 2:
binary_str2 = "11111111111111111111111111111101"
result2 = solution.reverseBits(binary_str2)
print(result2)  # Output: 3221225471
 
cs

 

 

관련 문제

리트코드 191번 Number of 1 bits 문제 풀이 링크

리트코드 268번 Missing number 문제 풀이 링크

리트코드 338번 Counting bits 문제 풀이 링크

리트코드 371번 Sum of two integers 문제 풀이 링크

 

 

 

190. Reverse Bits