表示数字的位数

2024-01-02

我正在尝试编写一个函数来返回小于 JavaScript 限制 (2^53)-1 的正整数位数。然而,我遇到了精度问题,并且希望避免使用大整数库。

方法一:

function bitSize(num)
{
return Math.floor( Math.log(num) / Math.log(2) ) + 1;
}

Pass: bitSize( Math.pow(2, 16) -1 ) = 16
Pass: bitSize( Math.pow(2, 16) ) = 17
Fail (Should be 48): bitSize( Math.pow(2, 48) -1 ) = 49 
Pass: bitSize( Math.pow(2, 48) ) = 49

方法二:

function bitSize(num)
{
var count = 0;
while(num > 0)
{
    num = num >> 1;
    count++;
}
return count;
}

Pass: bitSize( Math.pow(2, 16) -1 ) = 16
Pass: bitSize( Math.pow(2, 16) ) = 17
Fail (Should be 48): bitSize( Math.pow(2, 48) -1 ) = 1
Fail (Should be 49): bitSize( Math.pow(2, 48) ) = 1

我认为这两种方法都无法精确解决问题。

谁能建议一种适用于 0 -> 2^53-1 之间数字的替代方法

Thanks.


你可以做:

function bitSize(num) {
    return num.toString(2).length;
}

The toString() https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number/toString的方法Number将基数作为可选参数。

这里有一些tests http://jsfiddle.net/eke8f/。适用于 Chrome、Safari、Opera 和 Firefox。无法访问IE,抱歉。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

表示数字的位数 的相关文章

随机推荐