leetcode 231: 二的幂

每日一题 leetcode231
上图!在这里插入图片描述
二话不说,我直接重拳出击!

class Solution {
    public boolean isPowerOfTwo(int n) {
        int res = 0;
    
        while(n > 0){
            if((n & 1) == 1){
                res++;
            }
            n >>= 1;
        }
        return (res == 1);
    }
}

win + R 打开窗口输入calc 进入程序员模式 输入任何2的幂的数在二进制中都是只有 一个 ‘ 1 ’ 的,所以直接对整数n进行移位与位与操作。在这里插入图片描述
官方正解
在这里插入图片描述在这里插入图片描述
官方解释的很清楚,这里也不再赘述。

class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n & (n - 1)) == 0;
    }
}

class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && (n & -n) == n;
    }
}

这里的时间复杂度和空间复杂度都是O(1),显然官方答案更优。
方法二
根据题目“钻空子”在这里插入图片描述

class Solution {
    static final int BIG = 1 << 30;

    public boolean isPowerOfTwo(int n) {
        return n > 0 && BIG % n == 0;
    }
}

下面还有一种钻空子的方法,但不是官方的。

class Solution {
    public boolean isPowerOfTwo(int n) {
        switch (n) {
            case 1:
            case 2:
            case 4:
            case 8:
            case 16:
            case 32:
            case 64:
            case 128:
            case 256:
            case 512:
            case 1024:
            case 2048:
            case 4096:
            case 8192:
            case 16384:
            case 32768:
            case 65536:
            case 131072:
            case 262144:
            case 524288:
            case 1048576:
            case 2097152:
            case 4194304:
            case 8388608:
            case 16777216:
            case 33554432:
            case 67108864:
            case 134217728:
            case 268435456:
            case 536870912:
            case 1073741824:
            return true;
        }
        return false;
    }
}

时间复杂度都是O(1) hhhhhhh

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值