算法与数据结构之判断是否为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最大值为231-1,那么最大即为230,所以

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;
    }
};
posted @ 2017-07-27 12:16  vhyz  阅读(267)  评论(0编辑  收藏  举报