본문 바로가기
Computer/Algorithm

[LeetCode] 190. Reverse Bits - Kotlin

by HanDongWook 2025. 3. 2.
반응형

 

class Solution {
    fun reverseBits(n: Int): Int {
        var res = 0
        var num = n
        for (i in 0 until 32) {
            res = res shl 1        // 1. res를 왼쪽으로 1비트 이동
            res += num and 1       // 2. num의 최하위 비트를 res에 추가
            num = num shr 1        // 3. num을 오른쪽으로 1비트 이동
        }
        return res
    }
}

 

주요 비트 연산


  1. shl (Shift Left):
    • 비트를 왼쪽으로 이동. 오른쪽은 0으로 채워짐.
    • 예: 0010 shl 10100.
  2. shr (Shift Right):
    • 비트를 오른쪽으로 이동. 왼쪽은 부호 비트로 채워짐(음수면 1, 양수면 0).
    • 예: 0100 shr 10010.
  3. and (Bitwise AND):
    • 두 비트가 모두 1일 때만 1 반환.
    • num and 1은 최하위 비트(LSB)를 추출 (0 또는 1).


과정 상세 설명

 

입력 예시로 n = 13 (이진수: 00001101, 32비트로 확장)을 사용해 단계별로 살펴보겠습니다. 목표는 00001101을 뒤집어 10110000 (10진수 176)을 만드는 것입니다.

 

초기 상태

  • res = 0 (00000000).
  • num = 13 (00001101).

1단계: 루프 0~31

  • i = 0:
    1. res = res shl 1:
      • 0000000000000000 (아직 이동할 비트 없음).
    2. res += num and 1:
      • num = 00001101, num and 1 = 1 (최하위 비트 1).
      • res = 00000000 + 1 = 00000001.
    3. num = num shr 1:
      • 0000110100000110.
  • 상태: res = 00000001, num = 00000110.
  • i = 1:
    1. res = res shl 1:
      • 0000000100000010.
    2. res += num and 1:
      • num = 00000110, num and 1 = 0.
      • res = 00000010 + 0 = 00000010.
    3. num = num shr 1:
      • 0000011000000011.
  • 상태: res = 00000010, num = 00000011.
  • i = 2:
    1. res = res shl 1:
      • 0000001000000100.
    2. res += num and 1:
      • num = 00000011, num and 1 = 1.
      • res = 00000100 + 1 = 00000101.
    3. num = num shr 1:
      • 0000001100000001.
  • 상태: res = 00000101, num = 00000001.
  • i = 3:
    1. res = res shl 1:
      • 0000010100001010.
    2. res += num and 1:
      • num = 00000001, num and 1 = 1.
      • res = 00001010 + 1 = 00001011.
    3. num = num shr 1:
      • 0000000100000000.
  • 상태: res = 00001011, num = 00000000.
  • i = 4~31:
    • num이 이미 0이므로 num and 1 = 0.
    • res는 계속 왼쪽으로 이동하며 0 추가.
    • 최종: res = 10110000 (32비트로 확장: 00000000...10110000).

결과

  • 입력: 00001101 (13).
  • 출력: 10110000 (176).
반응형

'Computer > Algorithm' 카테고리의 다른 글

[LeetCode] 125. Valid Palindrome - kotlin  (0) 2025.03.02
[LeetCode] 191. Number of 1 Bits - Kotlin  (0) 2025.03.02
백준 9184  (0) 2022.11.27
Poisoned Reverse를 통한 Count to Infinity 문제 해결  (0) 2022.11.26
백준 6588  (0) 2022.10.10

댓글