Advertisement
326. Power of Three
EasyView on LeetCode
Time: O(log n)
Space: O(1)
Approach
Repeatedly divide by 3; the number is a power of three if and only if the result reduces to exactly 1.
326.cs
C#
// Approach: Repeatedly divide by 3; the number is a power of three
// if and only if the result reduces to exactly 1.
// Time: O(log n) Space: O(1)
public class Solution
{
public bool IsPowerOfThree(int n)
{
if (n == 0)
return false;
while (n % 3 == 0)
n /= 3;
return n == 1;
}
}
public class Solution1
{
public bool IsPowerOfThree(int n)
{
// 1162261467 is the maximum integer that is a power of three
// (it is 3^19, as 3^20 is bigger than int).
// If 'n' is a power of three, it must divide this number without a remainder.
// The condition 'n > 0' ensures that 'n' is positive,
// because negative numbers and zero cannot be powers of three.
return n > 0 && 1162261467 % n == 0;
}
}Advertisement
Was this solution helpful?