天天看点

【C语言】 LeetCode 326 Power of Three题目方法一:方法二:

题目

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;
}