File tree 1 file changed +14
-2
lines changed
1 file changed +14
-2
lines changed Original file line number Diff line number Diff line change 9
9
*/
10
10
public class RightmostSetBit {
11
11
12
+ /**
13
+ * Returns the position of the rightmost set bit
14
+ * in {@param n} where the position starts from 1.
15
+ * <p/>
16
+ * Works for -ve no.s as well.
17
+ *
18
+ * @param n
19
+ * @return
20
+ */
12
21
public static int getRightmostSetBitPosition (long n ) {
13
22
int position = 0 ;
14
- while (n > 0 ) {
23
+ while (n != 0 ) {
15
24
position ++;
16
25
if ((n & 1 ) == 1 ) {
17
26
break ;
@@ -22,7 +31,7 @@ public static int getRightmostSetBitPosition(long n) {
22
31
}
23
32
24
33
public static long unsetRightmostSetBit (long n ) {
25
- return n & (n - 1 );
34
+ return n & (n - 1 ); // brian kerningham's algorithm
26
35
}
27
36
28
37
public static void main (String a []) {
@@ -32,6 +41,9 @@ public static void main(String a[]) {
32
41
System .out .println (getRightmostSetBitPosition (5 ));
33
42
System .out .println (getRightmostSetBitPosition (18 ));
34
43
System .out .println (getRightmostSetBitPosition (19 ));
44
+ System .out .println (getRightmostSetBitPosition (-1 ));
45
+ System .out .println (getRightmostSetBitPosition (-2 ));
46
+ System .out .println (getRightmostSetBitPosition (-4 ));
35
47
36
48
System .out .println ("========================" );
37
49
You can’t perform that action at this time.
0 commit comments