Skip to content

Commit a4ed5d3

Browse files
committed
add solution: Reverse Bits
1 parent 76fb734 commit a4ed5d3

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

โ€Žreverse-bits/flynn.goโ€Ž

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
ํ’€์ด
3+
- ์›๋ณธ uint32 num์— ๋Œ€ํ•˜์—ฌ LSB๋ถ€ํ„ฐ(๊ฐ€์žฅ ์˜ค๋ฅธ์ชฝ bit) ํƒ์ƒ‰ํ•ฉ๋‹ˆ๋‹ค
4+
LSB % 2 == 1 -> uint32์˜ ์ƒˆ๋กœ์šด MSB์—(๊ฐ€์žฅ ์™ผ์ชฝ bit) 1 ์ถ”๊ฐ€
5+
else -> 0 ์ถ”๊ฐ€
6+
Big O
7+
- Time complexity: O(1)
8+
- input num์— ์ƒ๊ด€ ์—†์ด 32๋ฒˆ์˜ ๋ฐ˜๋ณต์„ ๊ณ ์ •์ ์œผ๋กœ ์‹คํ–‰ํ•ฉ๋‹ˆ๋‹ค
9+
- Space complexity: O(1)
10+
*/
11+
12+
func reverseBits(num uint32) uint32 {
13+
var res uint32 = 0
14+
for i := 0; i < 32; i++ {
15+
// using numerical operators
16+
// if num % 2 == 1 {
17+
// res = res * 2 + 1
18+
// } else {
19+
// res *= 2
20+
// }
21+
// num /= 2
22+
23+
// using bitwise operators
24+
res = (res << 1) | (num & 1)
25+
num >>= 1
26+
}
27+
28+
return res
29+
}

0 commit comments

Comments
ย (0)