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 >= 1)
        {
            if (n == 1 || n == 3)
                return true;
            else
            {                
                if (n % 3) break;
                n /= 3;
            }
        }
        return false;
    }
};
class Solution {  
public:  
    bool isPowerOfThree(int n) {  
        if (n < 1) return 0;  

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

        return maxPow3Val % n == 0;  
    }  
};

你可能感兴趣的:(LeetCode,Algorithm,C++,power,recursion)