326. Power of Three

xiaoxiao2021-02-28  97

题目:

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?

思路:

本题和前面的博客power of two的解题思路一样,但是题目尝试让我们不要使用循环与递归,所以本题给出非循环,非递归的方法。

代码(递归):

class Solution { public: bool isPowerOfThree(int n) { if(n==1) return true; else if(n<1) return false; else { if ((n/3.0) == (n/3)) return isPowerOfThree(n/3); else return false; } } }; 代码(非): class Solution { public: bool isPowerOfThree(int n) { // 1162261467 is 3^19, 3^20 is bigger than int return ( n>0 && 1162261467%n==0); } };

转载请注明原文地址: https://www.6miu.com/read-42869.html

最新回复(0)