算法与数据结构之判断是否为n的幂

231. Power of Two

本题有四种思路,一种一种道来

1.循环

class Solution {
public:
    bool isPowerOfTwo(int n) {
       if(n<=0) return false;
        while(n%2==0)
            n/=2;
        return n==1;
    }
};

2.递归

class Solution {
public:
    bool isPowerOfTwo(int n) {
      return n>0 && (n==1 || (n%2==0 && isPowerOfTwo(n/2)));  
    }
};

3.&运算符

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

4.数学方法

int最大值为2^31-1,那么最大即为2^30,所以

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

342. Power of Four

1.循环

class Solution {
public:
    bool isPowerOfFour(int num) {
        if(num<=0)
            return false;
        while(num%4==0)
            num/=4;
        return num == 1;
    }
};

2.递归

class Solution {
public:
    bool isPowerOfFour(int num) {
        return num>0 && (num == 1 ||(num%4==0 && isPowerOfFour(num/4)));
    }
};

3.&运算符

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

4.数学方法

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

注:该方法判断四的幂的二进制1的位置,若1的位置在奇数位,则才为4的幂

326. Power of Three

1.循环

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n<=0)
            return false;
        while(n%3==0)
            n/=3;
        return n==1;
    }
};

2.递归

class Solution {
public:
    bool isPowerOfThree(int n) {
        return n>0 && (n==1 || (n%3==0 && isPowerOfThree(n/3)));
    }
};

3.数学方法

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

转载于:https://www.cnblogs.com/vhyz/p/7244194.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值