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

[Codewars] Binary Addition (7 kyu) / JavaScript

by fluss 2022. 9. 29.

https://www.codewars.com/kata/551f37452ff852b7bd000139

 

Codewars - Achieve mastery through coding practice and developer mentorship

Coding practice 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:

Implement a function that adds two numbers together and returns their sum in binary. The conversion can be done before, or after the addition.

The binary number returned should be a string.

Examples:(Input1, Input2 --> Output (explanation)))

1, 1 --> "10" (1 + 1 = 2 in decimal or 10 in binary)
5, 9 --> "1110" (5 + 9 = 14 in decimal or 1110 in binary)

 

설명:

두 숫자를 더한 합을 이진수로 반환하는 함수를 구현하세요. 변환은 덧셈 전이나 후에 실행될 수 있습니다.

반환된 2진수는 문자열이어야 합니다.

예시:(Input1, Input2 --> Output (explanation)))

1, 1 --> "10" (1 + 1 = 2 in decimal or 10 in binary)
5, 9 --> "1110" (5 + 9 = 14 in decimal or 1110 in binary)

 

풀이

function addBinary(a,b) {
  return (a + b).toString(2);
}

toString을 사용해서 a, b의 합을 2진수로 바꾸었다.

 

참고

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Number/toString

 

Number.prototype.toString() - JavaScript | MDN

**toString() **메서드는 특정한 Number 객체를 나타내는 문자열을 반환합니다.

developer.mozilla.org

 

댓글