Leetcode:231. Power of Two(JAVA)

来源:互联网 发布:梦幻西游挂机软件 编辑:程序博客网 时间:2024/05/07 19:06

【题目描述】

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

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

【思路】

不用循环和递归,则:

2^x=n

log(2^x) = log(n)

x log(2) = log(n)

x = log(n) / log(2)

由于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(2);        return Math.abs(res-Math.round(res)) < temp;    }}


0 0