[LeetCode] Power of Two, Power of Three, Power of Four

407 查看

三道基本相同的题目,都可以用位操作、递归和迭代来做。

Power of Two

1. Bit Manipulation -- 2 ms beats 21.88%

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

2. Iteration -- 2 ms beats 21.88%

public class Solution {
    public boolean isPowerOfTwo(int n) {
        if (n > 1)
            while (n % 2 == 0) n /= 2;
        return n == 1;
    }
}

Power of Three

1. Recursion -- 20 ms beats 24%

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

2. Iteration -- 15-17 ms beats 72.54%-91.74%

public class Solution {
    public boolean isPowerOfThree(int n) {
        if (n > 1)
            while (n % 3 == 0) n /= 3;
        return n == 1;
    }
}

Power of Four

Bit Manipulation -- 2ms beats 22.59%

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

2. Iteration -- 2 ms beats 22.59%

public class Solution {
    public boolean isPowerOfFour(int n) {
        if (n > 1)
            while (n % 4 == 0) n /= 4;
        return n == 1;
    }
}