File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments