File tree Expand file tree Collapse file tree 1 file changed +50
-0
lines changed
Expand file tree Collapse file tree 1 file changed +50
-0
lines changed Original file line number Diff line number Diff line change 1+ package leetcode_study
2+
3+ /*
4+ * 주어진 32 bits unsigned integer를 뒤집는 문제
5+ * Bit 연산에 대한 개념이 전무해 String으로 치환 후 문제 해결
6+ * 작은 수는 표현할 수 있었지만 아래와 같이 문제를 해결할 경우 큰 수가 입력되었을 경우 부호 비트를 인식하여 음수로 표기합니다.
7+ * 또한 32 bit를 구성하기 위해 부족한 문자열을(자릿수) 추가하기 때문에 연산이 더해집니다.
8+ * */
9+ fun reverseBits1 (n : Int ):Int {
10+ val nStr = n.toString(2 )
11+ val totalLength = nStr.length
12+ var temp = " "
13+ if (totalLength != 32 ) {
14+ for (i in 0 until 32 - totalLength) {
15+ temp + = " 0"
16+ }
17+ }
18+ val fullBitString = temp + nStr
19+ var result = 0
20+
21+ for (i in (fullBitString.length - 1 ) downTo 0 ) {
22+ val eachBitValue = 2.0 .pow(i).toInt()
23+ if (fullBitString[i] == ' 0' ) {
24+ continue
25+ } else {
26+ result + = eachBitValue
27+ }
28+ }
29+ println (result.toString(2 ))
30+ return result
31+ }
32+
33+ /*
34+ * Bit 연산을 통한 Reverse Bit 구성
35+ * 시간 복잡도: O(32) (32비트의 숫자에 대해 반복)
36+ * 공간 복잡도: O(1) (상수 공간 사용)
37+ * */
38+ fun reverseBits (n : Int ): Int {
39+ var input = n
40+ var result = 0
41+
42+ for (i in 0 until 32 ) {
43+ // 결과에 현재 비트 추가
44+ result = (result shl 1 ) or (input and 1 )
45+ // 입력 비트를 오른쪽으로 이동
46+ input = input shr 1
47+ }
48+
49+ return result
50+ }
You can’t perform that action at this time.
0 commit comments