Skip to content

Commit 22b7af4

Browse files
committed
feat : reverse-bits
1 parent 98dfafb commit 22b7af4

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

reverse-bits/ekgns33.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/*
2+
input : 32 bit unsigned integer n
3+
output : unsigned integer representation of reversed bit
4+
constraint :
5+
1) input is always 32 bit unsigned integer
6+
2) implementation should not be affected by programming language
7+
8+
solution 1)
9+
10+
get unsigned integer bit representation
11+
12+
build string s O(n)
13+
reverse O(n)
14+
get integer O(n)
15+
16+
tc : O(n) sc : O(n)
17+
18+
solution 2) one loop
19+
20+
nth bit indicates (1<<n) if reverse (1<< (32 - n))
21+
add up in one loop
22+
return
23+
24+
tc : O(n), sc: O(1)
25+
26+
*/
27+
public class Solution {
28+
// you need treat n as an unsigned value
29+
static final int LENGTH = 32;
30+
public int reverseBits(int n) {
31+
int answer = 0;
32+
for(int i = 0; i < LENGTH; i++) {
33+
if(((1<<i) & n) != 0) {
34+
answer += (1 << (LENGTH - i - 1));
35+
}
36+
}
37+
return answer;
38+
}
39+
}

0 commit comments

Comments
 (0)