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

时间:2015-06-23 16:27:51

标签: javascript

我正在尝试计算基数为2的总和。有没有办法在不使用parseInt的情况下执行此操作?

Inserting 0: dave
Inserting 1: laura
Inserting 2: owen
Inserting 3: vick
Inserting 4: amr
Checking if the proper person's name is there: 
Reading 0:amr
Reading 1:amr
Reading 2:amr
Reading 3:amr
Reading 4:amr
Changing a single element of an array: 
Reading 0:amr
Reading 1:John
Reading 2:amr
Reading 3:amr
Reading 4:amr

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

2 个答案:

答案 0 :(得分:1)

#categories{
width: 95%;
padding: 50px;
font-size: 110%;
outline: 0;
color: #777;
-webkit-appearance: none;
-moz-appearance: none;
border: solid 5px #cacaca;
border-radius: 20px;
margin: 30px 0 10px 0;
background-color: #fff;
background-image: url(http://baligia.com/img/selectdown.png);
background-position: 96% 50%;
background-repeat: no-repeat;
background-size: 50px;
-moz-appearance: none;
}
#searchinput{
border: solid 5px #cacaca;
border-radius: 20px;
background: #fff;
color: #42454e;
padding: 6px 8px;
width: 95%;
outline: none;
font-size: 110%;
text-align: left;
padding: 50px 130px 50px 50px;
margin: 0 0 30px 0;
}

这应该有用,我还没有完全测试过它。但是应该可以工作!

编辑:

现在直接添加2个数字,它也应该有用。

response.routes[0].legs[0].steps

答案 1 :(得分:1)

首先,您需要定义一个按位数学函数,然后是您自己的转换函数。评论示例:

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>