leetocode (Power of Two)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hsx1612727380/article/details/85315286

Title:Power of Two    231

Difficulty:Easy

原题leetcode地址:   https://leetcode.com/problems/power-of-two/

1.  转换二进制

时间复杂度:O(n),一次一层while循环,n为转换后的二进制长度。

空间复杂度:O(1),没有申请额外空间。

    /**
     * 2的n次方,只有第一位是1,其他位都是0
     * @param n
     * @return
     */
    public static boolean isPowerOfTwo(int n) {

        int count = 0;

        while (n > 0) {
            count += n & 1;
            n >>= 1;
        }

        return count == 1;

    }

猜你喜欢

转载自blog.csdn.net/hsx1612727380/article/details/85315286
今日推荐