Reputation: 57
I want to find the power of 2 that any integer contains. Like 12 = 2*2*3 so answer should come as 2, 28 = 2*2*7 so answer should come as 2 and so on.
int powerOf2InNumber = (int)Math.floor(Math.log(number) / Math.log(2));
I tried the above code but in cases like 28,26,10 etc i'm getting wrong answer.
Upvotes: 4
Views: 1395
Reputation: 40057
The best way, imo, has already been provided using Integer.numberOfTrailingZeros
. It is taken from Hacker's Delight which is an excellent book and worth the price. Another method is as follows:
int b = 32*75;
int powerOf2 = BitSet.valueOf(new long[]{b}).nextSetBit(0);
System.out.println(powerOf2);
Prints
5
Note: For completeness you weren't far off in your attempt and logarithms can be used along with some basic bit manipulation. So you can do the following:
int number = 32*75;
int powerOf2 = (int)(Math.log(number & -number)/Math.log(2))
Upvotes: 0
Reputation: 509
What I think you're asking is: the number of times 2 goes into a number?
int countPowerOfTwo(int number) {
int count = 0;
while (abs(number) > 0) {
if (number % 2 != 0) {
return count;
}
count++;
number = number / 2;
}
return count;
}
Upvotes: 0
Reputation: 111
This should do the trick:
int check = 28;
int count = 0;
while(check % 2 == 0) {
check /= 2;
count++;
}
Check ends up as the other factor. I.e the 7 in 2 * 2 * 7. Count is your answer.
Upvotes: 0
Reputation: 64913
There is a handy built-in function,
int powersOf2 = Integer.numberOfTrailingZeros(number);
Upvotes: 12