A better way to solve whether a number is a power of 2

Question: Determine whether a number is a power of 2?

Solve the code: try to use bit operation will be faster than always dividing by 2 and taking the modulus

/**
 * 2的n次方的正整数代表:某个位是1,其他位是0
 * 负整数代表:连续为0 (取反 + 1 为真实表示的值)
 * 1...10
 * 1...00
 * 1..000
 */
public class BackDemo {

    public static boolean valid(int num){
        boolean isPositive = (num & (1 << 31)) == 0;
        return isPositive ? positive(num) : noPositive(num);
    }
    public static boolean positive(int num){
        int count = 0;
        for (int i = 30; i >=0; i--) {
            boolean bitIsZero = (num & (1 << i)) == 0;
            if(!bitIsZero){
                count ++;
                continue;
            }
        }
        return (count == 1);
    }

    public static boolean noPositive(int num){
        boolean begin = false;
        for (int i = 0; i <= 30; i++) {
            boolean bitIsZero = (num & (1 << i)) == 0;
            if(begin && bitIsZero){
                return false;
            }
            if(!bitIsZero && !begin){
                begin = true;
            }
        }
        return true;
    }
}

 

Guess you like

Origin blog.csdn.net/MrBack/article/details/115270037