判断一个数是2的幂次方

程序

public class Power2Algorithm {

    public static void main(String[] args) {
        System.out.println(isPower2(4));
        System.out.println(isPower2(6));
    }

    public static boolean isPower2(int num) {
        return (num&(num-1))==0;
    }
}

输出

true
false

主要用到2的幂 特性

bmax bn b(n-1) b2 b1 b0
num 0 0 1 0 0 0 0 0
num-1 0 0 0 1 1 1 1 1
num&(num-1)  == 0

猜你喜欢

转载自blog.csdn.net/qingguang686/article/details/112301388