函数在不使用parseInt的情况下求和以2为基数的数字的值

Function to sum the values of base-2 numbers without using parseInt

本文关键字:数字 情况下 函数 parseInt 求和      更新时间:2023-09-26

我正在尝试计算基数为2的数字的和。有没有一种方法可以在不使用parseInt的情况下做到这一点?

function calculate(num1, num2) {
     var a = parseInt(num1, 2);
     var b = parseInt(num2, 2);
     return a + b;
 }
calculate('101', '10')
//Returns 7

参见小提琴:http://jsfiddle.net/marcusdei/ko1wuq2u/1/

 function calculate(num1) {
     var j=num1.length;
     var arr=num1.split('');
     var num=0;
     for(var n=0;n<arr.length;n++)
      {
          if(j>=0)
          {
             num=num+(Math.pow(2,n)*arr[j-1]);
             j=j-1;
          }
      }
        alert(num);      
 }

这应该有效,我还没有完全测试过。但应该有效!

编辑:

这现在直接将2个数字相加,它也应该起作用。

var d=calculate('11','101');
alert(d);
function calculate(num1,num2) {
    var h=((num1.length>num2.length)?num2:num1);
    var h2=((num1.length>num2.length)?num1.length:num1.length);
    var secondnum;
    if(h==num2)
        secondnum=num1;
    else
        secondnum=num2;
    for(var x=0;x<=(h2-h.length);x++)
    {
        h='0'+h;  
    }
     var arr1=h.split('');
     var arr2=secondnum.split('');
     var j=arr1.length;
     var sum1=0;
     for(var n=0;n<arr1.length;n++)
      {
          if(j>0)
          {
              sum1=sum1+(Math.pow(2,n)*parseInt(arr1[j-1]));   
              sum1=sum1+(Math.pow(2,n)*parseInt(arr2[j-1]));
              j=j-1;
          }
      }
return sum1;    
}

首先需要定义一个逐位数学函数,然后定义自己的转换函数。带注释的示例:

function binaryAdd(a, b) {
  // Break each string down into "bits"
  var aBits = a.split('').reverse(),
    bBits = b.split('').reverse();
  // Pad the shorter value with zeroes
  while (aBits.length < bBits.length) {
    aBits.push('0');
  }
  while (bBits.length < bBits.length) {
    bBits.push('0');
  }
  // Add
  var carry = false,
    out = [];
  // For each bit
  for (var i = 0; i < aBits.length; ++i) {
    var s = 0 + (aBits[i] === '1') + (bBits[i] === '1') + carry;
    // This acts much as a lookup table:
    // 0 and 2 should print zeroes, 2 and 3 should carry to the next bit
    out.push('' + s % 2);
    carry = s > 1;
  }
  if (carry) {
    out.push('1');
  }
  // Flip and join
  return out.reverse().join('');
}
function parseBinary(n) {
  // Get the bits
  var nBits = n.split('').reverse();
  // Sum using the value of each position
  var sum = 0;
  for (var i = 0; i < nBits.length; ++i) {
    sum += nBits[i] * Math.pow(2, i);
  }
  return sum;
}
function showMath(a, b) {
  var c = binaryAdd(a, b);
  return '' + a + ' + ' + b + ' = ' + c + ' (' + parseBinary(c) + ')';
}
document.getElementById('a').textContent = showMath('101', '10');
document.getElementById('b').textContent = showMath('10111', '1011');
<pre id=a></pre>
<pre id=b></pre>

相关文章: