LeetCode(231): Power of Two

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

题意:给定一个整数,判断其是否是2幂次方。

思路:如果一个整数是2的幂次方的话,用二进制可以表示为100…的形式,如8可以表示为100。在二进制的表示形式下只有一个1。判断n的2进制中1的个数。

代码:

public boolean isPowerOfTwo(int n) {
         int cnt = 0;
        while (n > 0) {
            cnt += (n & 1);
            n >>= 1;
        }
        return cnt == 1;
    }
原文地址:https://www.cnblogs.com/Lewisr/p/5125420.html