題目
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
方法一:
由于整形存儲有大小限制,利用其大小限制可以快速求解。(一般用32位,4個位元組)
bool isPowerOfThree(int n) {
int const Max3PowerInt = 1162261467; // 3^19, 3^20 = 3486784401 > MaxInt32
if (n <= 0 || n > Max3PowerInt) return false;
return Max3PowerInt % n == 0;
}
方法二:
利用數學方法進行轉換計算,但是算法複雜度還是較高
bool isPowerOfThree(int n) {
int const Max3PowerInt = 1162261467; // 3^19, 3^20 = 3486784401 > MaxInt32
if (n <= 0 || n > Max3PowerInt) return false;
return Max3PowerInt % n == 0;
}