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

这三个题看似一样,其实各有不同的解法,基本解法就是如下一种
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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值