Skip to content

Commit 52f365a

Browse files
Add Index Of Right Most Set Bit Test (TheAlgorithms#4325)
* add Index Of Right Most Set Bit Test * clang linter solved
1 parent 4bcddd3 commit 52f365a

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
/**
4+
* Find The Index Of Right Most SetBit
5+
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
6+
*/
7+
8+
public class IndexOfRightMostSetBit {
9+
public static int indexOfRightMostSetBit(int n) {
10+
if (n == 0) {
11+
return -1; // No set bits
12+
}
13+
14+
// Handle negative numbers by finding the two's complement
15+
if (n < 0) {
16+
n = -n;
17+
n = n & (~n + 1); // Get the rightmost set bit in positive form
18+
}
19+
20+
int index = 0;
21+
while ((n & 1) == 0) {
22+
n = n >> 1;
23+
index++;
24+
}
25+
26+
return index;
27+
}
28+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.thealgorithms.bitmanipulation;
2+
3+
import static org.junit.jupiter.api.Assertions.*;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
/**
8+
* Test case for Index Of Right Most SetBit
9+
* @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi)
10+
*/
11+
12+
class IndexOfRightMostSetBitTest {
13+
14+
@Test
15+
void testIndexOfRightMostSetBit() {
16+
assertEquals(3, IndexOfRightMostSetBit.indexOfRightMostSetBit(40));
17+
assertEquals(-1, IndexOfRightMostSetBit.indexOfRightMostSetBit(0));
18+
assertEquals(3, IndexOfRightMostSetBit.indexOfRightMostSetBit(-40));
19+
}
20+
}

0 commit comments

Comments
 (0)