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?
<Solution>Could you do it without using any loop / recursion?
在 Power of Two 這題,因為 2 的次方數特性,可以從判斷有幾個為 1 的 bit 來得到答案
但是 3 的次方數沒有這個特性
這時候需要用到 log 的換底公式 log3n = log10n / log103
如果 n 是 3 的次方數,那麼 log3n 為整數
所以題目就變成判斷 log10n / log103 是否為整數
要判斷數自 X 是否為整數,可以用這個方式 X - int(X) == 0
code如下(參考資料)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
public: | |
bool isPowerOfThree(int n) { | |
return n > 0 && !(log10(n) / log10(3) - static_cast<int>(log10(n) / log10(3))); | |
} | |
}; |
沒有留言:
張貼留言