LeetCode专题:231. Power of Two

Power of Two

Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true 
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false

解答

public class PowerOfTwo {
    public static boolean isPowerOfTwo(int n) {

        //方法一 n如果能被2整除,那么最后n=n/2 最后肯定等于1
//         if (n<=0) return false; //2的多少次方都不可能为负数
//         if (n==1) return true;
//         while (n % 2 == 0){ //判断n能被2整除
//             n/=2;
//         }
//         if (n == 1) return true;
//         return false;

        /**  我们看看能被2整除的数转化为2进制
         *  4   100
         *  8   1000
         *  16  10000
         *  32  100000
         *  64  1000000
         *  ....
         *
         *  任意一个二进制减一再& n  (n&(n-1))=0
         *   16  10000
         *      -    1
         *       01111
         *
         *     10000
         *   & 01111
         *     00000
         *
         *   也就是任何一个能被2整除的数  n&(n-1)=0
         */
        if ((n & (n-1)) == 0){
            return true;
        }
        return false;
    }
}

猜你喜欢

转载自blog.csdn.net/yu0_zhang0/article/details/81749898