본문 바로가기
알고리즘/Codewars

[Codewars] Ones and Zeros (7 kyu) / JavaScript

by fluss 2022. 12. 28.

https://www.codewars.com/kata/578553c3a1b8d5c40300037c

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

Given an array of ones and zeroes, 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

However, the arrays can have varying lengths, not just limited to 4.

 

설명:

1과 0으로 이루어진 배열을 받아 동등한 이진수 값을 정수로 반환하세요.

 

예: [0, 0, 0, 1]은 1의 이진 표현인 0001로 취급됩니다.

 

예시:

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

그러나 배열의 길이는 4로 제한되지 않고 다양한 길이를 가질 수 있습니다.

 

풀이

배열을 문자열로 만들고 10진수로 바꿔서 반환해주었다.
 

코드

const binaryArrayToNumber = arr => {
  return parseInt(arr.join(''), 2);
};

댓글