7kyu Ones and Zeros
Posted tong24
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了7kyu Ones and Zeros相关的知识,希望对你有一定的参考价值。
题目:
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的主要内容,如果未能解决你的问题,请参考以下文章