3 的幂

下面这段代码能ac,但是他不能判断负次幂的结果

1
2
3
4
5
6
7
8
9
10
11
12
/**
* @param {number} n
* @return {boolean}
*/
var isPowerOfThree = function (n) {
if (n === 1) return true;
let i = 3;
while (i < n) {
i *= 3;
}
return i === n;
};

换底公式
logₐ(b) = logₓ(b) / logₓ(a)

1
2
3
4
5
6
7
8
9
10
function isPowerOfThree(n) {
if (n <= 0) return false;
// n=Math.pow(3,x)
// x=log3(n)=loge(n)/loge(3)
const logResult = Math.log10(n) / Math.log10(3);
return Number.isInteger(logResult);
}

// logₐ(b) = logₓ(b) / logₓ(a)


本站由 ao 使用 Stellar 1.29.1 主题创建。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。