我真的很执着于为 JavaScript 创建一个函数。
我知道如何在心里进行从二进制到十进制的数学运算,但我不知道如何写出来。 我无法使用 parse int 或 to string。
我并不是要求任何人为我做这件事,我只是想知道从哪里开始的一些想法。
function BintoDec(x)
{
var number = x
任何帮助都是很好的帮助。 提前致谢
编辑
我能够想出这个函数,但我最终得到 0 作为我的输出。 救命!
function BinToDec(x) {
var result = 0;
var multiple = 1;
for (var i = 0; i < x.length; i++)
{
var digit = x[x.length - 1 - i];
if (digit == '1') {
result += multiple;
}
multiple *= 2;
}
return result;
}
print(BinToDec(101));
最佳答案
I am not asking anyone to do this for me I would just like some ideas on where to start
你可以使用这个:-
var digit = parseInt(binary, 2);
另请检查parseInt
编辑:-(没有看到您不想使用 parseInt)
您可以尝试循环遍历字符串并尝试如下:-
for(i = 0; i < len; i++)
{
r = r * 2 + (arr[i] == '1' ? 1 : 0);
}
关于javascript - 不使用 parseInt 的二进制到十进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19435586/