tags:

views:

207

answers:

4

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?

A: 

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

Scott Evernden
+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
oh, did you mean you need a good way?
mobrule
+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
Why not use Long.highestOneBit?
Yishai
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