The code for displaying the least power 2 is greater than or equal to an integer

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

+3
source share
5 answers
i>1 ? Integer.highestOneBit(i-1)<<1 : 1

Obviously, it suffers from integer overflow (a strict solution in intdoes not exist strictly for half positive ints).

Regular disclaimer: not verified or compiled.

+6
source
int nextPow2(int n) {
  if (n <= 1) return n;
  double d = n - 1;
  return 1 << ((Double.doubleToRawLongBits(d) >> 52) - 1022);
}

, .

0
source
if (i==0) return 1;
else if (i==1) return 2;
else if (i==2 || i==3) return 4;
else if (i==4 || i==5 || i==6 || i==7) return 8;
else if (...)
-1
source

you can do this by counting the number of unsigned right shifts until the result is zero

-2
source

Source: https://habr.com/ru/post/1718337/


All Articles