File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed
main/java/com/thealgorithms/bitmanipulation
test/java/com/thealgorithms/bitmanipulation Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments