326. Power of three

Source: Internet
Author: User

Given an integer, write a function to determine if it is a power of three.

Follow up:
Could do it without using any loop/recursion?

Idea 1: Use recursive functions to solve the problem, if n<=0, returns false. If n==1, returns True. If n can be divisible by 3, the function is called recursively with N/3. Otherwise, n cannot be divisible by 3, and naturally it cannot be a power of 3, returning false.

classSolution { Public:    BOOLIspowerofthree (intN) {if(n<=0)            return false; if(n==1)            return true; if(n%3==0)            returnIspowerofthree (n/3); return false; }};
Idea 2: Using the log function, if LOG3 (n) is an integer, then the power of N is 3. However, the use of the log function will result in rounding problems, which are caused by precision. We can take special measures to determine whether n is equal to 3 Log3 (n), in order to circumvent round off error, we take POW (3,round (LOG3 (n))), round function to calculate the LOG3 (n) is rounded.
class Solution {public:    bool ispowerofthree (int  n) {          If(n<1)            returnfalse;         return N==pow (3, round (log (n)/log (3)));}    ;



326. Power of three

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.