LeetCode - 231/326/342 - Power of Two/Three/Four

231. Power of Two

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

判断一个数是不是2的幂。我写的是不断地除以2除以2除以2,很一般的思路。

看评论区有一个很巧的做法,感觉超优雅!是2的幂就表明这个数的二进制只能有一个1,那样(n & (n - 1))就应该为0。凡是不为0的,肯定不是2的幂。

时间复杂度O(1),空间复杂度0

class Solution {
public:
    bool isPowerOfTwo(int n) {
        return n > 0 && !(n & (n-1));
    }
};



326. Power of Three

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

Follow up:
Could you do it without using any loop / recursion?

想了很久很久以后,分析了一波二进制以后。。。还是只会写循环。。。(为什么我会去分析二进制,那是2进制又不是3进制【扶额】)

看到评论区的做法后,感觉自己。。。

3^20 > INT_MAX,我们取3^19,只要是3的幂,就一定能被3^19取余为0。(本来还想这样会不会有错,发现他所有的因子都是3的幂,唔,那就肯定没错了)

class Solution {
public:
    bool isPowerOfThree(int n) {
        return n > 0 && (1162261467 % n == 0);
    }
};


342. Power of Four

Given an integer (signed 32 bits), write a function to check whether it is a power of 4.

Example:
Given num = 16, return true. Given num = 5, return false.

Follow up: Could you solve it without loops/recursion?

是否是4的幂。

是4的幂就一定是2的幂,然后再排除是2的幂就可以了

评论区高票答案排除的方法是(num & 0x55555555) != 0。(就是8个0101,刚好32位)

class Solution {
public:
    bool isPowerOfFour(int num) {
        return num > 0 && !(num & (num-1)) && ((num - 1) % 3 == 0);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值