Java Ceil ceilingPowerOf2(final int n)

Here you can find the source of ceilingPowerOf2(final int n)

Description

Computes the ceiling power of 2 within the range [1, 2^30].

License

Apache License

Parameter

Parameter Description
n The input argument.

Return

the ceiling power of 2.

Declaration

public static int ceilingPowerOf2(final int n) 

Method Source Code

//package com.java2s;
/*//from   w  w w .  j  a v a  2  s. c  o m
 * Copyright 2015-16, Yahoo! Inc.
 * Licensed under the terms of the Apache License 2.0. See LICENSE file at the project root for terms.
 */

public class Main {
    /**
     * Computes the ceiling power of 2 within the range [1, 2^30]. This is the smallest positive power
     * of 2 that equal to or greater than the given n. <br>
     * For:
     * <ul>
     * <li>n &le; 1: returns 1</li>
     * <li>2^30 &le; n &le; 2^31 -1 : returns 2^30</li>
     * <li>n == a power of 2 : returns n</li>
     * <li>otherwise returns the smallest power of 2 greater than n</li>
     * </ul>
     *
     * @param n The input argument.
     * @return the ceiling power of 2.
     */
    public static int ceilingPowerOf2(final int n) {
        if (n <= 1) {
            return 1;
        }
        final int topPwrOf2 = 1 << 30;
        return (n >= topPwrOf2) ? topPwrOf2 : Integer.highestOneBit((n - 1) << 1);
    }
}

Related

  1. ceiling_float_int(float value)
  2. ceilingAbs(double a)
  3. ceilingHalf(int num)
  4. ceilingNextPowerOfTwo(final int x)
  5. ceilingPow2(int n)
  6. ceilingPowerOf2(int n)
  7. ceilingPowerOfTwo(final int a)
  8. ceilingPowerOfTwo(int value)
  9. ceilInt(Double d, double intv)