1294. Power of Three
Given an integer, write a function to determine if it is a power of three.
Example
Example1
Input: n = 0
Output: False
Example2
Input: n = 9
Output: True
Challenge
Could you do it without using any loop / recursion?
Input test data (one parameter per line)How to understand a testcase?
解法1:
class Solution {
public:
/**
* @param n: an integer
* @return: if n is a power of three
*/
bool isPowerOfThree(int n) {
int num = 1;
while(num <= n) {
if (num == n) return true;
num *= 3;
}
return false;
}
};
解法2:
class Solution {
public:
/**
* @param n: an integer
* @return: if n is a power of three
*/
bool isPowerOfThree(int n) {
if (n == 0 || n == 1) return n;
if (n % 3 != 0) return false;
return isPowerOfThree(n / 3);
}
};
本文介绍了一种方法,用于确定一个给定的整数是否可以表示为3的幂次方。提供了两种解决方案,一种使用循环逐步乘以3进行比较,另一种采用递归方式除以3直到无法整除。这两种方法都有效地解决了问题,但递归方法可能在某些情况下更简洁。
2859

被折叠的 条评论
为什么被折叠?



