forked from DaleStudy/leetcode-study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEcoFriendlyAppleSu.kt
50 lines (45 loc) ยท 1.45 KB
/
EcoFriendlyAppleSu.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package leetcode_study
/*
* ์ฃผ์ด์ง 32 bits unsigned integer๋ฅผ ๋ค์ง๋ ๋ฌธ์
* Bit ์ฐ์ฐ์ ๋ํ ๊ฐ๋
์ด ์ ๋ฌดํด String์ผ๋ก ์นํ ํ ๋ฌธ์ ํด๊ฒฐ
* ์์ ์๋ ํํํ ์ ์์์ง๋ง ์๋์ ๊ฐ์ด ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ ๊ฒฝ์ฐ ํฐ ์๊ฐ ์
๋ ฅ๋์์ ๊ฒฝ์ฐ ๋ถํธ ๋นํธ๋ฅผ ์ธ์ํ์ฌ ์์๋ก ํ๊ธฐํฉ๋๋ค.
* ๋ํ 32 bit๋ฅผ ๊ตฌ์ฑํ๊ธฐ ์ํด ๋ถ์กฑํ ๋ฌธ์์ด์(์๋ฆฟ์) ์ถ๊ฐํ๊ธฐ ๋๋ฌธ์ ์ฐ์ฐ์ด ๋ํด์ง๋๋ค.
* */
fun reverseBits1(n:Int):Int {
val nStr = n.toString(2)
val totalLength = nStr.length
var temp = ""
if (totalLength != 32) {
for (i in 0 until 32 - totalLength) {
temp += "0"
}
}
val fullBitString = temp + nStr
var result = 0
for (i in (fullBitString.length - 1) downTo 0) {
val eachBitValue = 2.0.pow(i).toInt()
if (fullBitString[i] == '0') {
continue
} else {
result += eachBitValue
}
}
println(result.toString(2))
return result
}
/*
* Bit ์ฐ์ฐ์ ํตํ Reverse Bit ๊ตฌ์ฑ
* ์๊ฐ ๋ณต์ก๋: O(32) (32๋นํธ์ ์ซ์์ ๋ํด ๋ฐ๋ณต)
* ๊ณต๊ฐ ๋ณต์ก๋: O(1) (์์ ๊ณต๊ฐ ์ฌ์ฉ)
* */
fun reverseBits(n: Int): Int {
var input = n
var result = 0
for (i in 0 until 32) {
// ๊ฒฐ๊ณผ์ ํ์ฌ ๋นํธ ์ถ๊ฐ
result = (result shl 1) or (input and 1)
// ์
๋ ฅ ๋นํธ๋ฅผ ์ค๋ฅธ์ชฝ์ผ๋ก ์ด๋
input = input shr 1
}
return result
}