Power of Three

LeetCode #326


Description:

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?

Example:

Note

Idea:

一种generic的方法用iteration,另一种用log10来搞

Code:

Iteration方法:

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n<=0) return false;

        while(n!=1){
            if((n/3)*3!=n) return false;
            n=n/3;
        }
        return true;

    }
};

O(1)方法

class Solution {
public:
    bool isPowerOfThree(int n) {
        if(n<=0) return false;

        // double fmod (double numer, double denom);
        // Compute remainder of division
        return fmod(log10(n)/log10(3), 1)==0;
    }
};

results matching ""

    No results matching ""