Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit ffa2a73

Browse files
author
Ram swaroop
committed
reverse bits done in an obvious way
1 parent dfe893b commit ffa2a73

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/me/ramswaroop/bits/ReverseBits.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,34 @@ public static int getNumberByReversingBits(int n) {
3434
return n;
3535
}
3636

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+
3763
public static void main(String a[]) {
3864
System.out.println(getNumberByReversingBits(7));
65+
System.out.println(getNumberByReversingBits_V1(7));
3966
}
4067
}

0 commit comments

Comments
 (0)