标签:code style 示例 ret mat time 完整 isp 计算
一:解题思路
方法一:可以采用前面讲解的类似的2的幂来做这道题,Time:O(log_3(n)),Space:O(1)
方法二:整数最大值,y=2^31-1。3^a<=y,那么a<=log_ay ==> a<=ln(y)/ln(3),计算出a为19.所以MAX_NUM=3^19。Time:O(1),Space:O(1)
二:完整代码示例 (C++版和Java版)
方法一C++:
class Solution { public: bool isPowerOfThree(int n) { if (n <= 0) return false; while (n % 3 == 0) n /= 3; return n == 1; } };
方法一Java:
class Solution { public boolean isPowerOfThree(int n) { if(n<=0) return false; while(n%3==0) { n/=3; } return n==1; } }
方法二C++:
class Solution { public: int MAX_POWER = (int)(log(2147483647) / log(3)); int MAX_NUM = (int)pow(3, MAX_POWER); bool isPowerOfThree(int n) { return n > 0 && (MAX_NUM%n==0); } };
方法二Java:
class Solution { private final int MAX_POWER=(int)(Math.log(Integer.MAX_VALUE)/Math.log(3)); private final int MAX_NUM=(int)(Math.pow(3,MAX_POWER)); public boolean isPowerOfThree(int n) { return n>0 && (MAX_NUM%n)==0; } }
标签:code style 示例 ret mat time 完整 isp 计算
原文地址:https://www.cnblogs.com/repinkply/p/12628937.html