mirror of
https://github.com/TheAlgorithms/Java.git
synced 2025-07-07 17:56:02 +08:00
Add Index Of Right Most Set Bit Test (#4325)
* add Index Of Right Most Set Bit Test * clang linter solved
This commit is contained in:

committed by
GitHub

parent
4bcddd323c
commit
52f365a915
@ -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;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user