Power Of Two

 Given an integer, write a function to determine if it is a power of two.

我的解决方式:

好久不刷了,没感觉,这个解决方式比较差,下面有一个比较好的解决办法:

public class Solution {
    public boolean isPowerOfTwo(int n) {
            if (1 == n) {
            return true;
        }
        int remainder = 0;    // 余数
        int result = n;        //
        while (0 == remainder && 0 < result) {
            remainder = result%2;
            result = result/2;
            if (0 == remainder && 1 == result) {
                return true;
            }
        }
        return false;
    }
}

看到是2的幂,脑子里有寻找规律的想法,但是没有仔细思考。下方用的二进制的方式 & 为位运算符

public static boolean isPowerOfTwo(int n) {
         return n < 1 ? false : (n & (n - 1)) == 0 ? true : false;
    }
原文地址:https://www.cnblogs.com/tf-Y/p/5178579.html