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?
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.
See this link
Algorithm for finding the smallest power of two that’s greater or equal to a given value
Bye.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With