Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Code for displaying the smallest power of 2 greater than or equal than the integer

Tags:

java

I need a code in Java that can find the smallest power of 2 greater than or equal to any non-negative integer entered by the user. Can anyone help?


2 Answers

i>1 ? Integer.highestOneBit(i-1)<<1 : 1

Obviously suffers from integer overflow (there isn't a strictly correct solution in int for around half of positive ints).

Usual disclaimer: Not tested or compiled.

like image 177
Tom Hawtin - tackline Avatar answered Jan 31 '26 04:01

Tom Hawtin - tackline


See this link

Algorithm for finding the smallest power of two that’s greater or equal to a given value

Bye.

like image 23
RRUZ Avatar answered Jan 31 '26 04:01

RRUZ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!