Java Power of 2 nextPowerOf2(int n)

Here you can find the source of nextPowerOf2(int n)

Description

Returns the nearest power of 2, which is either n if n is already a power of 2, or the next higher number than n which is a power of 2.

License

Open Source License

Declaration

public static int nextPowerOf2(int n) 

Method Source Code

//package com.java2s;

public class Main {
    /**// w  w  w . j a  v  a 2s  .com
     * Returns the nearest power of 2, which is either n if n is already
     * a power of 2, or the next higher number than n which is a power of 2.
     */
    public static int nextPowerOf2(int n) {
        int x = 1;

        while (x < n) {
            x <<= 1;
        }

        return x;
    }
}

Related

  1. nextPower(int v, int power)
  2. nextPower2(int n)
  3. nextPowerOf2(final int n)
  4. nextPowerOf2(int n)
  5. nextPowerOf2(int n)
  6. nextPowerOf2(int n)
  7. nextPowerOf2(int v)
  8. nextPowerOf2(int x)