diff --git a/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java b/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java new file mode 100644 index 000000000..4b1ca51e5 --- /dev/null +++ b/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java @@ -0,0 +1,28 @@ +package com.thealgorithms.bitmanipulation; + +/** + * Find The Index Of Right Most SetBit + * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + */ + +public class IndexOfRightMostSetBit { + public static int indexOfRightMostSetBit(int n) { + if (n == 0) { + return -1; // No set bits + } + + // Handle negative numbers by finding the two's complement + if (n < 0) { + n = -n; + n = n & (~n + 1); // Get the rightmost set bit in positive form + } + + int index = 0; + while ((n & 1) == 0) { + n = n >> 1; + index++; + } + + return index; + } +} \ No newline at end of file diff --git a/src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java b/src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java new file mode 100644 index 000000000..f377793cf --- /dev/null +++ b/src/test/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBitTest.java @@ -0,0 +1,20 @@ +package com.thealgorithms.bitmanipulation; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.Test; + +/** + * Test case for Index Of Right Most SetBit + * @author Bama Charan Chhandogi (https://github.com/BamaCharanChhandogi) + */ + +class IndexOfRightMostSetBitTest { + + @Test + void testIndexOfRightMostSetBit() { + assertEquals(3, IndexOfRightMostSetBit.indexOfRightMostSetBit(40)); + assertEquals(-1, IndexOfRightMostSetBit.indexOfRightMostSetBit(0)); + assertEquals(3, IndexOfRightMostSetBit.indexOfRightMostSetBit(-40)); + } +} \ No newline at end of file