I assume I understand the problem correctly, based on your equivalent code in Kotlin:
`val shift = Integer.toBinaryString(number).count { it == '0' }`,
that it suffices to count zeroes, not trailing zeroes.
I believe int suffices for the ranges you have. Thus your idea of doing:
int given = 262144;
String binaryString = Integer.toBinaryString(given);
will work.
int zeros = binaryString.length() - binaryString.replaceAll("0", "").length();
will give you the number of zeroes, which is your answer.
If so, though, and really all the zeroes are trailing, it seems likely (though I cannot be sure from the question) that we're always looking at a 1 followed by n zeroes. To find n, we could then also do:
(int)Math.round(Math.log(given)/Math.log(2.0))
to find the number of zeroes. Or for that matter, if we continue with the string approach, there would be no need to explicitly count the zeroes. Rather,
int zeros= binaryString.length()-1;
would suffice.
REVISION:
There is something inelegant about all of the above. We are given an int which was 1 shifted left by any whole number from 0 to 28. We ought to be able to undo that without real number operations or strings, simply by shifting right until we get back to 1. Since our numbers are all > 0, we can use >>>, though >> (or /=2) would also do.
If the given int were given
, the following puts the number of zeroes in count
.
int temp = given;
int count = 0;
while (temp>1){
count++;
temp=temp>>>1;
}