3

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.

4 Answers4

10

There is a handy built-in function,

int powersOf2 = Integer.numberOfTrailingZeros(number);
harold
  • 61,398
  • 6
  • 86
  • 164
  • It might be worth mentioning for the uninitiated that this is the number of trailing zeroes of a binary string of the number and not the decimal number. Of course there's always the JavaDoc. – WJS Jun 07 '20 at 00:54
0

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.

Matt
  • 111
  • 7
0

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;
} 
Alec
  • 479
  • 4
  • 6
0

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))

WJS
  • 36,363
  • 4
  • 24
  • 39