leetcode解题之231# Power of Two&326. Power of Three Java版 (判断是否为2,或者3 的幂)

这篇博客主要讲解了如何用Java解决LeetCode的231题(Power of Two)和326题(Power of Three)。对于2的幂,通过检查整数的二进制表示中是否有且仅有一个1来判断;对于3的幂,使用数学方法,将问题转化为求解x = log(n) / log(3)是否为整数。
摘要由CSDN通过智能技术生成

231. Power of Two

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

求一个整数是不是2的幂

如果是power of two, 则2进制表达中,有且仅有一个1.  可以通过移位来数1的个数, 即判断   N & (N-1) 能把N中最右侧一个1变为0,即 N & (N-1)是否为0判断、

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

采用递归的方式判断,若是2的幂,最后退出条件为n=1

public boolean isPowerOfTwo(int n) {
		if (n == 1)
			return true;
		if (n >= 2 && n % 2 == 0)
			return isPowerOfTwo(n / 2);
		return false;
	}

326. Power of Three

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

Follow up:
Could you do it without using any loop / recursion?

【思路】

不用循环和递归,则:

3^x=n

log(3^x) = log(n)

x log(3) = log(n)

x = log(n) / log(3)

由于JAVA double浮点型的问题,需判断Math.abs(x - Math.round(x)) < 10e-15

public class Solution {
	public boolean isPowerOfThree(int n) {
		double temp = 10e-15;
		if (n == 0)
			return false;
		double res = Math.log(n) / Math.log(3);
		//精度问题,Math.round四舍五入函数
		return Math.abs(res - Math.round(res)) < temp;
	}
}
补充:

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值