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?
Asked
Active
Viewed 1,811 times
3
-
1Eclipse is a programming language? Uh oh. – a paid nerd Sep 23 '09 at 00:19
-
Eclipse is an IDE what language? Plus this smells of a homework question. What have you tried? – David Basarab Sep 23 '09 at 00:19
-
1I would like to see the solution in Visual Studio instead. – Ed S. Sep 23 '09 at 00:22
-
Sorry it asked me to tag it with something so I just chose Eclipse. The language is Java and I'm honestly not sure of where to begin on it aside from prompting for an interger and making sure that it is postive. – Sep 23 '09 at 00:25
6 Answers
7
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 int
s).
Usual disclaimer: Not tested or compiled.

Tom Hawtin - tackline
- 145,806
- 30
- 211
- 305
-
-
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 Sep 23 '09 at 02:56
0
int nextPow2(int n) {
if (n <= 1) return n;
double d = n - 1;
return 1 << ((Double.doubleToRawLongBits(d) >> 52) - 1022);
}
Fastest solution I have found on desktop.

hoford
- 4,918
- 2
- 19
- 19
0
Smallest power of 2 greater than or equal to a
// Next higher power of 2 greater than or equal to a
public static int nextPow2(int a) {
int r0, r1, r2, r3, r4;
r0 = 2 * highestOneBit(a - 1);
r1 = highestOneBit(a - 1) << 1;
r2 = (int) pow(2, ceil(log(a) / log(2)));
r3 = (int) pow(2, ceil(log10(a) / log10(2)));
r4 = (int) pow(2, 32 - numberOfLeadingZeros(a - 1));
return r0; // or r1 or r2 or r3 or r4
}
Exponent of the smallest power of 2 greater than or equal to a
// Exponent of next higher power of 2 greater than or equal to a
public static int nextpow2(int a) {
int r0, r1, r2;
r0 = (int) ceil(log(a) / log(2));
r1 = (int) ceil(log10(a) / log10(2));
r2 = (int) 32 - numberOfLeadingZeros(a - 1); // ceil(log2(x)) = 32 - numberOfLeadingZeros(x - 1)
return r0; // or r1 or r2
}

Hermann
- 7
- 2
-1
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 (...)

mob
- 117,087
- 18
- 149
- 283
-2
you can do this by counting the number of unsigned right shifts until the result is zero

Scott Evernden
- 39,136
- 15
- 78
- 84