Given an integer n
, write a function to determine if it is a power of three. An integer n
is a power of three if there exists an integer x
such that n == 3^x
.
n
?
n
can be any 32-bit signed integer, which means it can range from -2^31
to 2^31 - 1
.n
be negative or zero?
false
, as powers of three are positive numbers.-2^31
to 2^31 - 1
).Initial Check: If n
is less than or equal to zero, return false
immediately, since powers of three are always positive.
n
by 3 continuously:
n
is greater than 1, check if n
is divisible by 3.false
because n
cannot be a power of three.n
by 3 and continue the loop.n
is reduced to 1, return true
.n
is a power of three:
n
is positive, compute log(n) / log(3)
. If the result is an integer, then n
is a power of three.Here is the C++ implementation of the iterative approach:
#include <iostream>
using namespace std;
bool isPowerOfThree(int n) {
if (n <= 0) return false;
while (n % 3 == 0) {
n /= 3;
}
return n == 1;
}
int main() {
int test1 = 27; // Expected: true (3^3)
int test2 = 0; // Expected: false
int test3 = 9; // Expected: true (3^2)
int test4 = 45; // Expected: false
cout << std::boolalpha;
cout << "Is " << test1 << " a power of three? " << isPowerOfThree(test1) << endl;
cout << "Is " << test2 << " a power of three? " << isPowerOfThree(test2) << endl;
cout << "Is " << test3 << " a power of three? " << isPowerOfThree(test3) << endl;
cout << "Is " << test4 << " a power of three? " << isPowerOfThree(test4) << endl;
return 0;
}
O(log3(n))
, where log3
is the logarithm base 3. This is because in each iteration, we divide n
by 3. The number of divisions needed is proportional to log3(n)
.O(1)
, no extra space required other than variables.This method ensures that we efficiently determine whether n
is a power of three, taking into account all edge cases, including negative numbers and zero.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?