Leetcode 326 power of three (power of 3) (recursive, log function)

Source: Internet
Author: User

translation
给定一个整型数,写一个函数决定它是否是3的幂(翻译可能不太合适……跟进:你是否可以不用任何循环或递归来完成。
Original
anintegerwriteafunction to determine if it is a power of three.doitwithoutusingany loop / recursion?
Analysis

Test instructions I really do not understand, for example, 12 in the end can it? Or is it only: 3, 9, 27, 81? Let's write a simple recursion and try it.

bool isPowerOfThree(int n) {    if1returntrue;    elseif0returnfalse;    elseif30)        return3);    elsereturnfalse;}

Submitted successfully, then you use 12 as a parameter to try it, found to return false, then you can conclude that test instructions is the above I said the second kind.

Do you remember the log function, before a problem has been encountered, so this time to think of ...

log n 3

If calculated in 12来:

log a 3 =2.26186

INT( log a 3 )=2

log a 3 ?INT( log a 3 )=0.26186

So the direct judgment of whether the result is 0 is good ...

bool isPowerOfThree(int n) {    doubleloglog(3);                 returnint0truefalse;}

However, this code is submitted after the discovery is still wrong, 243 in the above code is actually false, break point to see should be due to the accuracy problem, so continue to change.

log n 3 = log n Ten log 3 Ten

So the code comes out ...

Code
class Solution {public:    bool isPowerOfThree(int n) {        doublelog10log10(3);        returnint0truefalse;    }};

Leetcode 326 power of three (power of 3) (recursive, log function)

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.