判断是否为n的幂

231. Power of Two

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

循环

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

递归

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

&运算符

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

数学方法

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

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

342. Power of Four

循环

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

递归

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

&运算符

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

数学方法

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

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

326. Power of Three

循环

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

递归

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

数学方法

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