Skip to content

Commit 4ed403d

Browse files
authored
Create 190.ReverseBits.kt
1 parent 945c058 commit 4ed403d

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

190.ReverseBits.kt

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Created by VINAY on 11-08-2024.
3+
* Github:@vinayByte
4+
*
5+
* time complexity of the reverseBits function is O(1)
6+
*/
7+
class Solution {
8+
// you need treat n as an unsigned value
9+
fun reverseBits(n: Int): Int {
10+
//n = 1101
11+
var result = 0
12+
var input = n
13+
14+
//i == 0
15+
for (i in 0 until 32) {
16+
val bit = input and 1 //1101 AND 0001 -> 0001
17+
val reverseBit = bit shl (31 - i) //1 shl (31-0) -> 10000000000000000000000000000000
18+
result =
19+
result or reverseBit // 00000000000000000000000000000000 OR 10000000000000000000000000000000 -> 10000000000000000000000000000000
20+
input = input shr 1 // 1101 shr 1 -> 0110 // index 1- > 0011, 2 -> 0001, 3 -> 0000
21+
}
22+
return result
23+
}
24+
}

0 commit comments

Comments
 (0)