Sponsored
Sponsored
This approach leverages the fact that if a number n
is a power of three, it should be divisible by 3 repeatedly until it becomes 1. If at any step, n
is not divisible by 3 and it's greater than 1, it cannot be a power of three.
Time Complexity: O(log n)
Space Complexity: O(1)
1#include <iostream>
2using namespace std;
3
4bool isPowerOfThree(int n) {
5 if (n < 1) return false;
6 while (n % 3 == 0) {
7 n /= 3;
8 }
9 return n == 1;
10}
The C++ function performs the same operations as the C function, using a while loop to verify divisibility by 3.
This approach uses logarithms to determine if a number is a power of three. By taking the logarithm of the number and comparing it to the logarithm base 3, we can check if they form an integer ratio.
Time Complexity: O(1)
Space Complexity: O(1)
1using System;
2
public class Solution {
public bool IsPowerOfThree(int n) {
if (n < 1) return false;
double logRes = Math.Log10(n) / Math.Log10(3);
return (logRes - (int)logRes) == 0;
}
}
This C# solution uses logarithmic calculations similar to other languages to determine if a number is a power of three.