天天看点

leetcode笔记: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?

二. 题目分析

题目的大意很简单,给出一个整数,判断这个整数是不是3的整数次幂。下面提示尽量不适用循环和递归来实现,因此这里给出两种实现方法,其中第一种循环方式的耗时更少。

三. 示例代码

class Solution {
public:
    bool isPowerOfThree(int n) {
        while (n >= )
        {
            if (n ==  || n == )
                return true;
            else
            {                
                if (n % ) break;
                n /= ;
            }
        }
        return false;
    }
};
           
class Solution {  
public:  
    bool isPowerOfThree(int n) {  
        if (n < ) return ;  

        int maxPow3 = log10(INT_MAX) / log10();
        int maxPow3Val = pow(, maxPow3);  

        return maxPow3Val % n == ;  
    }  
};