Dare2Solve
The task is to determine whether a given integer n
is a power of three. A number is considered a power of three if it can be written as (3^k), where (k) is a non-negative integer.
Powers of three grow exponentially, meaning they increase very quickly as the exponent increases. Since there is a limited range of integers that we need to check (from (3^0) to (3^30), since (3^31) exceeds the maximum value of a typical 32-bit integer), we can iterate through these powers and see if any of them match n
.
n
.true
. If no match is found by the time you reach (3^30), return false
.n
is less than 1, as negative numbers and zero can never be powers of three.class Solution {
public:
bool isPowerOfThree(int n) {
for (int i = 0; i < 31; i++) {
long long pow = powl(3, i);
if (pow == n) {
return true;
}
}
return false;
}
};
class Solution:
def isPowerOfThree(self, n: int) -> bool:
for i in range(31):
if 3 ** i == n:
return True
return False
class Solution {
public boolean isPowerOfThree(int n) {
for (int i = 0; i < 31; i++) {
double pow = Math.pow(3, i);
if (pow == n) {
return true;
}
}
return false;
}
}
var isPowerOfThree = function(n) {
for(let i=0;i<31;i++){
let pow=Math.pow(3,i)
if(pow===n){
return true
}
}
return false
};