码迷,mamicode.com
首页 > 其他好文 > 详细

7kyu Ones and Zeros

时间:2017-08-08 13:55:45      阅读:148      评论:0      收藏:0      [点我收藏+]

标签:pre   integer   string   bsp   reg   regex   example   nes   reduce   

题目:

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

标签:pre   integer   string   bsp   reg   regex   example   nes   reduce   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!