当前位置:网站首页>Leetcode-326. Power of 3

Leetcode-326. Power of 3

2022-07-23 05:19:00 KGundam

Mathematical problems


Topic details

Given an integer , Write a function to determine if it is 3 Power square . If it is , return true ; otherwise , return false .
Integers n yes 3 To the power of : There are integers x bring n == 3^x


Example 1:

 Input :n = 27
 Output :true

Example 2:

 Input :n = 0
 Output :false

Example 3:

 Input :n = 9
 Output :true

Example 4:

 Input :n = 45
 Output :false

Ideas :
The first method : Using logarithm . set up logn3 = m, If n yes 3 Integer power of , that m It must be an integer .

class Solution 
{
    
public:
    bool isPowerOfThree(int n) 
    {
    
        //logn3 = log10(n) / log10(3)
        //fmod(n, 1) Judge n Is it an integer , Is to return 0 
        return fmod(log10(n) / log10(3), 1) == 0;

    }
};

Another opportunistic method : Because in int Within the scope of 3 The largest power of is 3^19 = 1162261467, If n yes 3 An integer of
Fang , that 1162261467 Divide n The remainder of must be zero ; vice versa .

class Solution 
{
    
public:
    bool isPowerOfThree(int n) 
    {
    
        return n > 0 && 1162261467 % n == 0;
    }
};
原网站

版权声明
本文为[KGundam]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/204/202207221754000781.html