[LeetCode]Power of Four/Power of Three/Power of Two(Java)

来源:互联网 发布:2017网络效应判断题 编辑:程序博客网 时间:2024/06/05 15:02
这三个题看似一样,其实各有不同的解法,基本解法就是如下一种
public class Solution {    public boolean isPowerOfTwo(int n) {        System.out.println(Math.log10((double)n)/Math.log10((double)2));        System.out.println(Math.log((double)n)/Math.log((double)2));        return Math.log10((double)n)/Math.log10((double)2)%1==0;    }}

log()和log10()效果,不太一样,差距在小数点位上,为防止错误可以选择log10,或者log保留几位小数


最快的解法当然是位运算

Power of Four这个题的一种位远算方法如下

public class Solution {public boolean isPowerOfFour(int num) {return Integer.toBinaryString(num).matches("1(00)*");}}

还有一种是这样做的(高实在是高)

 public boolean isPowerOfFour(int num) {        return num > 0 && (num&(num-1)) == 0 && (num & 0x55555555) != 0;        //0x55555555 is to get rid of those power of 2 but not power of 4      

根据上面的一种方法针对Power of Two我写了下面的代码

public class Solution {     public boolean isPowerOfTwo(int n) {         <pre class="markdown-highlight"><code class="hljs java"><span class="hljs-keyword">        return</span> n <= <span class="hljs-number">0</span> ? <span class="hljs-keyword">false</span> : (n & (n - <span class="hljs-number">1</span>)) == <span class="hljs-number">0</span>;</code>

    }
}



2016/8/27



0 0
原创粉丝点击