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?
views:
207answers:
4
+3
A:
See this link
Algorithm for finding the smallest power of two that’s greater or equal to a given value
Bye.
RRUZ
2009-09-23 00:21:20
A:
you can do this by counting the number of unsigned right shifts until the result is zero
Scott Evernden
2009-09-23 00:29:23
+1
A:
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 (...)
mobrule
2009-09-23 01:26:56
oh, did you mean you need a good way?
mobrule
2009-09-23 01:30:21
+3
A:
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.
Tom Hawtin - tackline
2009-09-23 01:36:48
Well, you could do, but if you started with an `int`, you probably want an `int` result anyway. Also you can't do that for `long`. Arbitrary precision integers ftw!
Tom Hawtin - tackline
2009-09-23 02:56:56