【Leetcode】326. Power of Three

来源:互联网 发布:centos 打开80端口 编辑:程序博客网 时间:2024/06/03 19:47

方法一:

思路:递归,时间复杂度:O(lg(n)),空间复杂度:O(lg(n))。

public class Solution {    public boolean isPowerOfThree(int n) {        if (n <= 0)            return false;        if (n == 1)            return true;        if (n % 3 == 0)            return isPowerOfThree(n / 3);        else             return false;    }}

Runtime:18ms


方法二:

思路:反复除以3,最终一定等于1:时间复杂度:O(lg(n)),空间复杂度:O(1)。

public class Solution {    public boolean isPowerOfThree(int n) {        if (n <= 0)            return false;        int i = n;        for (; i % 3 == 0; i = i / 3);        if (i == 1)            return true;        else            return false;    }}

Runtime:18ms


方法三:

思路:

任何一个3的x次方一定能被int型里最大的3的x次方整除。

public class Solution {    public boolean isPowerOfThree(int n) {        if (n > 0 && 1162261467 % n == 0)            return true;        return false;    }}

Runtime:17ms


方法四:

思路:

3^x=n

log(3^x) = log(n)

x log(3) = log(n)

x = log(n) / log(3)一定是整数

rint():返回最接近参数的整数,如果有2个数同样接近,则返回偶数的那个。

它有两个特殊的情况:1)如果参数本身是整数,则返回本身。2)如果不是数字或无穷大或正负0,则结果为其本身。

public class Solution {    public boolean isPowerOfThree(int n) {        double res = Math.log(n) / Math.log(3);          if (Math.abs(res - Math.rint(res)) < 0.0000000001)            return true;        return false;    }}

Runtime:23ms


方法五:

思路:

也可以用if (Math.abs(res - Math.round(res)) < 0.0000000001)判断。

不能用if (Math.abs(res - (int)res) < 0.0000000001)判断,int强制类型转换是舍去而不是求最接近的整数。

public class Solution {    public boolean isPowerOfThree(int n) {        double res = Math.log(n) / Math.log(3);          if (Math.abs(res - Math.round(res)) < 0.0000000001)            return true;        return false;    }}

Runtime:19ms

1 0
原创粉丝点击