I tried to do the problem Find first set bit in Geeks for Geeks, and this is the code I used.
public static int getFirstSetBitPos(int n){
int counter = 0;
while (n > 0){
if ((n&1) == 1){
return counter + 1;
}
n >>= 1;
counter ++;
}
return 0;
}
The problem asks to solve it in a time complexity of O(logN), and my code is O(N). When I looked at the editorial, it had this solution.
// Java Code for Position of rightmost set bit
class GFG {
public static int getFirstSetBitPos(int n)
{
return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
}
// Drive code
public static void main(String[] args)
{
int n = 12;
System.out.println(getFirstSetBitPos(n));
}
}
// This code is contributed by Arnav Kr. Mandal
I don't understand this return (int)((Math.log10(n & -n)) / Math.log10(2)) + 1;
I would appreciate if someone could explain.
I am new to programming and an aspiring competitive programmer.
an aspiring competitive programmer
might want to know/mentionint Integer.numberOfTrailingZeros(int i)
.) $\endgroup$ – greybeard Nov 22 '20 at 14:19