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)