Given a number, this number is greater than the smallest to find the n-th power of 2

Two days look HashMap source, which has a saw algorithm, when a programmer configured hashmap hashmap if the capacity of a given n-th power of 2 is not, this should give it greater than a minimum number and the n-th power of 2 . See the source code inside, suddenly feeling scared to Heaven. Very admire those engineers developed written language of the underlying database.

Maybe in the future work will encounter this demand:

 

 

 

1. | =: is the bitwise or assignment and meaning.

2 >>>: indicates unsigned binary number to the right moving, after moving in front of all 0s.

public int MIN_POWER_TWO(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return n + 1;
    }

Guess you like

Origin www.cnblogs.com/songjinzhao/p/11583421.html