首页 > 其他 > 详细

7kyu Ones and Zeros

时间:2017-08-08 13:18:34      阅读:303      评论:0      收藏:0      [点我收藏+]

题目:

Given an array of one‘s and zero‘s convert the equivalent binary value to an integer.

Eg: [0, 0, 0, 1] is treated as 0001 which is the binary representation of 1

Examples:

Testing: [0, 0, 0, 1] ==> 1
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 0, 1] ==> 5
Testing: [1, 0, 0, 1] ==> 9
Testing: [0, 0, 1, 0] ==> 2
Testing: [0, 1, 1, 0] ==> 6
Testing: [1, 1, 1, 1] ==> 15
Testing: [1, 0, 1, 1] ==> 11

 

答案:

// 1
const binaryArrayToNumber = arr => parseInt(arr.join(‘‘), 2);

// 2
function binaryArrayToNumber (arr) {
  return arr.reduce( (a, b) => a << 1 | b);
}

// 3
const binaryArrayToNumber = arr => {
  var regexComma = arr.toString().replace(/,/g, ‘‘);
  return parseInt(regexComma, 2);
}

7kyu Ones and Zeros

原文:http://www.cnblogs.com/tong24/p/7306271.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!