Files
Java/src/main/java/com/thealgorithms/bitmanipulation/IndexOfRightMostSetBit.java
Piotr Idzik f010a47608 chore: enforce InsertNewlineAtEOF in clang-format (#4343)
* style: insert newline at eof

* style: use `InsertNewlineAtEOF` in `clang-format`

* fix: use `clang-format-16`

* chore: update clang-format-lint-action to v0.16.2

---------

Co-authored-by: Debasish Biswas <debasishbsws.dev@gmail.com>
2023-09-01 04:10:46 +00:00

29 lines
664 B
Java

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;
}
}