Skip to content

Commit 5747260

Browse files
committed
reverse bits solved
1 parent 79627ed commit 5747260

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

reverse-bits/mintheon.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
public class Solution {
2+
/**
3+
시간복잡도: O(1) -> 루프는 항상 32번 반복되기 때문
4+
공간복잡도: O(1)
5+
*/
6+
7+
// you need treat n as an unsigned value
8+
public int reverseBits(int n) {
9+
int answer = 0;
10+
int index = 31;
11+
12+
while(n != 0) {
13+
// n&1 : 마지막 비트를 추출
14+
// << : 0을 패딩처리 시켜서 상위 자리수로 올려버림
15+
answer += (n & 1) << index;
16+
17+
// >>> : 부호 상관없이 오른쪽으로 비트 이동
18+
n = n >>> 1;
19+
index--;
20+
}
21+
22+
return answer;
23+
}
24+
}

0 commit comments

Comments
 (0)