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?

Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.

给一个整数,写一个函数来判断此数是不是3的次方数。

类似的题目Power of Two 中,由于2的次方数的特点,用位操作很容易。而3的次方数没有显著的特点,最直接的方法就是不停地除以3,最后判断是否能整除。

follow up是否不用任何循环或递归。

解法1: 循环

解法2: 迭代

解法3:取对数

Java:

class Solution {
public boolean isPowerOfThree(int n) {
return n > 0 && Math.pow(3, Math.round(Math.log(n) / Math.log(3))) == n;
}
}  

Python:

class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0: return False
while n != 1:
if n % 3 != 0: return False
n /= 3
return True 

Python:

class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0: return False
if n == 1: return True
return n % 3 == 0 and self.isPowerOfThree(n / 3) 

Python:

class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and 3 ** round(math.log(n, 3)) == n

Python:

class Solution(object):
def isPowerOfThree(self, n):
return n > 0 and (math.log10(n)/math.log10(3)).is_integer()

Python:  

class Solution(object):
def __init__(self):
self.__max_log3 = int(math.log(0x7fffffff) / math.log(3))
self.__max_pow3 = 3 ** self.__max_log3 def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and self.__max_pow3 % n == 0

C++:

class Solution {
public:
bool isPowerOfThree(int n) {
if(n <= 0) return false;
while(n > 1){
if(n %3 != 0) return false;
n/=3;
}
return true;
}
};  

C++:

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

C++:

class Solution {
public:
bool isPowerOfThree(int n) {
return n > 0 && pow(3, round(log(n) / log(3))) == n;
}
};

  

  

All LeetCode Questions List 题目汇总

最新文章

  1. Windows Azure Storage (6) Windows Azure Storage之Table
  2. codeforces 632+ E. Thief in a Shop
  3. 【日常小问题】windows系统操作技巧
  4. 页面打开自动触发onlick事件
  5. [译]ASP.NET 5: New configuration files and containers
  6. WCF实现客户端自动更新
  7. 面向GC的Java编程
  8. hdu1869六度分离(dijkstra)
  9. Android异步载入全解析之IntentService
  10. JAVA基础——方法笔记
  11. git 命令提交文件
  12. TestNg 6.异常测试
  13. Python中将array类型不按科学计数法存在文件中的方法
  14. java学习笔记20(Arraylist复习,Collection接口方法,迭代器,增强型for循环)
  15. 在pypi上发布python包详细教程
  16. bzoj1830 Y形项链
  17. MATLAB安装libsvm无法使用解决办法(转)
  18. python(33)多进程和多线程的区别
  19. LeetCode——Palindrome Number
  20. Java第二次作业--数组和String类

热门文章

  1. CentOS7下的AIDE入侵检测配置
  2. Vue和微信小程序区别
  3. C# 利用log4net 把日志写入到数据库
  4. ajax、axios、fetch 对比
  5. HTTP Status 500 - DateConverter does not support default String to &#39;Date&#39; conversion.错误
  6. How to Start Up an Open Source Company
  7. 如何打开.ipynb文件
  8. java 库存管理
  9. Windows加载器与模块初始化
  10. jedis的连接池