0%

leetcode Power of Three

leetcode Power of Three

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?

题目地址: leetcode Power of Three

题目大意:

给定一个整数,判断是否是3的整数幂

思路

方法一

循环判断,每次除以3

C++

1
2
3
4
5
6
7
8
9
10
11
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;
}
};

Python

1
2
3
4
5
6
7
8
9
10
11
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

方法二

递归

C++

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

 

Python

1
2
3
4
5
6
7
8
9
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)

 

方法三

取对数

C++

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

Java

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

Python

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

 

本文是leetcode 326 Power of Three 题解,更多本博客题解见 https://www.hrwhisper.me/leetcode-algorithm-solution/

请我喝杯咖啡吧~