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