File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change @@ -34,7 +34,34 @@ public static int getNumberByReversingBits(int n) {
34
34
return n ;
35
35
}
36
36
37
+ /**
38
+ * Checks for set bits in {@param n} and sets them
39
+ * from the left end in {@code reverseNum}.
40
+ * <p/>
41
+ * Time Complexity: O(log n)
42
+ * Space Complexity: O(1)
43
+ *
44
+ * @param n
45
+ * @return
46
+ */
47
+ public static int getNumberByReversingBits_V1 (int n ) {
48
+ System .out .println (Integer .toBinaryString (n ));
49
+
50
+ int reverseNum = 0 , i = 0 ;
51
+ while (n > 0 ) {
52
+ if ((n & 1 ) == 1 ) {
53
+ reverseNum |= 1 << 31 - i ;
54
+ }
55
+ n >>= 1 ;
56
+ i ++;
57
+ }
58
+ System .out .println (Integer .toBinaryString (reverseNum ));
59
+
60
+ return reverseNum ;
61
+ }
62
+
37
63
public static void main (String a []) {
38
64
System .out .println (getNumberByReversingBits (7 ));
65
+ System .out .println (getNumberByReversingBits_V1 (7 ));
39
66
}
40
67
}
You can’t perform that action at this time.
0 commit comments