PowerOfTwo [source code]

public class PowerOfTwo {
static

public class Solution {
    public boolean isPowerOfTwo(int n) {
        return n > 0 && Integer.toBinaryString(n).matches("^10*$");
    }
}

    public static void main(String[] args) {
        PowerOfTwo.Solution tester = new PowerOfTwo.Solution();
    }
}

这题也可以用PowerOf3类似的方法,因为 int 范围内2最多只能到30(2 ^ 31 - 1), 所以枚举也可以.
不过这题其实更简单, 2的 string 表达是直接就有的, 所以用 string 的方式最直接, 尽管不一定很快;

不过这一题有一个陷阱, 就是MIN_VALUE 也在 case 里面; 所以直接加一个判断n>0就行了;

好像这几个 power 题都是只考虑正数.

这个做法直接, 但是速度很慢, 21(1)的速度;

类似的, 这个是 submission 最优解:

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

discussion有一个比较 sleek 的解:

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

这个n & (n - 1)的东西好像前面有一题碰到过?
想起来了, 是 CountingBits 的时候碰到过, 当时循环做这个处理来完成remove rightmost bit 1的操作;

另一个思路:

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

虽然老是想着最优解, 不过类似:

return n>0 && (n==1 || (n%2==0 && isPowerOfTwo(n/2)));

这样的解, 也要会写. power 用 recursion 是最直接的;


Problem Description

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

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Difficulty:Easy
Category:Algorithms
Acceptance:39.95%
Contributor: LeetCode
Companies
google
Related Topics
math bit manipulation
Similar Questions
Number of 1 Bits Power of Three Power of Four

results matching ""

    No results matching ""