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

    Example 1:

    1. Input: 1
    2. Output: true
    3. Explanation: 20 = 1

    Example 2:

    1. Input: 16
    2. Output: true
    3. Explanation: 24 = 16

    Example 3:

    1. Input: 218
    2. Output: false

    题意

    判断一个整数是不是2的幂。

    思路

    见代码。


    代码实现

    1. class Solution {
    2. public boolean isPowerOfTwo(int n) {
    3. if (n <= 0) {
    4. return false;
    5. }
    6. while (n % 2 == 0) {
    7. n /= 2;
    8. }
    9. return n == 1;
    10. }
    11. }