326. Power of three

Source: Internet
Author: User

Topic:

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?

Answer:

Determines whether a number is a power of 3 and cannot be used in loops and recursion:

Since 3 is a prime number, so if one is a power of 3, then any of its approximations is also a power of 3.

So the idea is to find the largest 3 power of int, divided by the number we need to judge, and if the remainder is 0, the number is the power of 3.

Or a long long to find a power greater than the maximum value of int 3 is also possible.

1 classSolution {2  Public:3     BOOLIspowerofthree (intN) {4         intmax,m;5Max= (numeric_limits<int>:: Max) (); 6M=pow (3,((int) (log (max)/log (3))));7             return(n>0&& (m%n==0));8     }9};

Note: ^ is an XOR symbol in a bitwise operation, not a power-seeking symbol.

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.