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