題目
Power of Three
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?
Credits:
Special thanks to @dietpepsi for adding this problem and creating all test cases.
Subscribe to see which companies asked this question
分析
題目本身是一道easy的題目,但是有要求不用循環和遞歸這個就有些麻煩了。
思路一
不能用循環和遞歸那麼就從3的冪的幾個數之間尋找聯繫,於是列了幾個數(3,9,27)觀察了一陣,並沒有結論,(pass)
思路二
既然數都列出來了那麼就一個個比較就是了,思路比較粗暴就直接列代碼了
bool isPowerOfThree(int n) {
switch(n)
{
case 1:return true;
case 3:return true;
case 9:return true;
case 27:return true;
case 81:return true;
case 243:return true;
case 729:return true;
case 2187:return true;
case 6561:return true;
case 19683:return true;
case 59049:return true;
case 177147:return true;
case 531441:return true;
case 1594323:return true;
case 4782969:return true;
case 14348907:return true;
case 43046721:return true;
case 129140163:return true;
case 387420489:return true;
case 1162261467:return true;
case 3486784401:return true;//int範圍內最大的是3^19
default: return false;
}
}
但是提交的結果要140ms。
思路三
思路二中對每個數字的判斷只進行了20次左右的比較運算,但是在結果排名比較靠後。所以在思考許久未果之後,又瀏覽了討論區,有了新方法。
bool isPowerOfThree(int n) {
return n>0 && !(1162261467 % n) ;
}
//if(n是3的冪)那麼 3^19 % n == 0
但是即使是這樣,最後排名也只有69%。還有一種思路就是log3(n),取3的對數。但是這樣感覺並不會比思路三更快。
後續
參考了官方給出的解答,方法應該是沒錯的,可能是leetcode運行時的問題導致某些提交的運行時間更短。