您的位置:首页 > 编程语言 > Java开发

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

2017-03-19 12:52 477 查看

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息