Skip to content

Commit f5b1049

Browse files
author
Ram swaroop
committed
rightmost setbit workable for -ve nos: done
1 parent e88a8ae commit f5b1049

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

src/me/ramswaroop/bits/RightmostSetBit.java

+14-2
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,18 @@
99
*/
1010
public class RightmostSetBit {
1111

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+
*/
1221
public static int getRightmostSetBitPosition(long n) {
1322
int position = 0;
14-
while (n > 0) {
23+
while (n != 0) {
1524
position++;
1625
if ((n & 1) == 1) {
1726
break;
@@ -22,7 +31,7 @@ public static int getRightmostSetBitPosition(long n) {
2231
}
2332

2433
public static long unsetRightmostSetBit(long n) {
25-
return n & (n - 1);
34+
return n & (n - 1); // brian kerningham's algorithm
2635
}
2736

2837
public static void main(String a[]) {
@@ -32,6 +41,9 @@ public static void main(String a[]) {
3241
System.out.println(getRightmostSetBitPosition(5));
3342
System.out.println(getRightmostSetBitPosition(18));
3443
System.out.println(getRightmostSetBitPosition(19));
44+
System.out.println(getRightmostSetBitPosition(-1));
45+
System.out.println(getRightmostSetBitPosition(-2));
46+
System.out.println(getRightmostSetBitPosition(-4));
3547

3648
System.out.println("========================");
3749

0 commit comments

Comments
 (0)