Java脚本将号码转换为字符串底座两个
我正在进行一个测试,任务是编写一个将整数作为输入的函数,并返回该数字的二进制表示中等于二进制表示的位数。您可以保证输入是非负的。
因此,我有以下问题:虽然我的代码在大多数情况下运行良好,并且在输入为9843520790和8989787640时通过所有测试通过,但我得到的结果错误。因此,我希望计算出来,并将这个数字二进制和尝试了几个console.log(bnum),我注意到的是我在转换过程中松开了高字节。意味着Bnum =(N>>> 0).ToString(2); Console.Log(BNUM)返回1100100111111111111101111110011 for 7676570995何时应返回11100100110011001111111111011111110011。
var countBits = function(n) {
let bNum=(n>>>0).toString(2);//converts int to base 2
console.log(bNum);
let sum=0;
for(let i=0;i<=bNum.length-1;i++)
{
if(bNum[i]==1)
sum+=1;
}
return sum;
};
我不是在要求某人解释为什么会发生这种情况,以便我可以找到解决方案的方法。
I am doing a test and the task is to write a function that takes an integer as input, and returns the number of bits that are equal to one in the binary representation of that number. You can guarantee that input is non-negative.
So i have the following problem : while my code runs ok for the most part and passes all tests when the inputs are 9843520790 and 8989787640 I am getting wrong results. So I hoped in the calc and made this numbers binary and tried couple of console.log(bNum) and what I noticed is that I loose the high byte during the conversion. Meaning that after bNum=(n>>>0).toString(2); the console.log(bNum) returns 11001001100011110010110101110011 for 7676570995 when it should return 111001001100011110010110101110011.
var countBits = function(n) {
let bNum=(n>>>0).toString(2);//converts int to base 2
console.log(bNum);
let sum=0;
for(let i=0;i<=bNum.length-1;i++)
{
if(bNum[i]==1)
sum+=1;
}
return sum;
};
I am not asking for a coding solution just someone to explain why this is happening so I can find a wayto fix it.Thanks in advance :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您的问题是
n&gt;&gt; 0
。我不熟悉&gt;&gt;&gt; 0
,但据我所知,它将输入转换为未签名的32位。uint的最大值是4294967295
因此这些数字超过了它。因此,我认为转换中丢失了一些信息。。
I think your issue is
n>>>0
. I not to familiar with the>>>0
but as far as I know it converts the input to a 32bit unsigned in. The max value for an uint is4294967295
so those numbers exceed it. Therefore I think some information is lost in the conversion..