Josh
Josh

Reputation:

Code for displaying the smallest power of 2 greater than or equal than the integer

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?

Upvotes: 3

Views: 1907

Answers (6)

Hermann
Hermann

Reputation: 11

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
    }

Upvotes: 0

hoford
hoford

Reputation: 5323

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.

Upvotes: 0

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

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.

Upvotes: 7

mob
mob

Reputation: 118635

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 (...)

Upvotes: -1

Scott Evernden
Scott Evernden

Reputation: 39946

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

Upvotes: -2

Related Questions