[프로그래머스] 이진수 더하기

stella·2023년 1월 8일
0

Algorithm

목록 보기
8/40
post-thumbnail

문제

이진수를 의미하는 두 개의 문자열 bin1bin2가 매개변수로 주어질 때, 두 이진수의 합을 return하도록 solution 함수를 완성해주세요.


parseInt()

  • parseInt() 는 정수로의 형변환 뿐만 아니라 문자열을 파싱하여 특정 진수의 정수를 반환해주는 기능도 갖고 있다.
const string = "10";
console.log(parseInt(string)); // 10 (string을 정수로)
console.log(parseInt(string, 2)); // 2 (2진수인 string을 10진수로)

toString()

  • toString() 은 문자열로 형변환 뿐만 아니라, number 타입의 경우 선택적으로 기수 (2 ~ 36)를 매개변수로 취하여, 이를 통해 10진수를 특정진수로 변환한 값을 return 해준다.
const number = 10;
console.log(number.toString()); // "10" (number을 문자열로)
console.log(number.toString(2)); // "1010" (number을 2진수로)

코드

  • 2진수 → 10진수: parseInt() 사용
  • 10진수 → 2진수: toString() 사용
function solution(bin1, bin2) {
    return (parseInt(bin1, 2) + parseInt(bin2, 2)).toString(2);
}
profile
Frontend Engineer

0개의 댓글