Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the exponent of 2 in an integer in Java?

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.

like image 829
UnscrewedChaff Avatar asked Sep 05 '25 03:09

UnscrewedChaff


1 Answers

There is a handy built-in function,

int powersOf2 = Integer.numberOfTrailingZeros(number);
like image 92
harold Avatar answered Sep 07 '25 21:09

harold