저장을 습관화

프로그래머스 LV.0 이진수 더하기 본문

코딩 테스트/프로그래머스 - 자바스크립트

프로그래머스 LV.0 이진수 더하기

ctrs 2023. 9. 27. 23:03

프로그래머스 LV.0 이진수 더하기

https://school.programmers.co.kr/learn/courses/30/lessons/120885

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

1. 문제 명

이진수 더하기


2. 문제 설명

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


3. 제한 사항

  • return 값은 이진수를 의미하는 문자열입니다.
  • 1 ≤ bin1, bin2의 길이 ≤ 10
  • bin1과 bin2는 0과 1로만 이루어져 있습니다.
  • bin1과 bin2는 "0"을 제외하고 0으로 시작하지 않습니다.


4. 예시

bin1 bin2 result
"10" "11" "101"
"1001" "1111" "11000"


5. 기본 제공 코드

function solution(bin1, bin2) {
    var answer = '';
    return answer;
}


6. 제출한 내 답

const solution = (bin1, bin2) => {
  return (parseInt(bin1, 2) + parseInt(bin2, 2)).toString(2);
};

 

6-2. VSC에 작성한 내용

const solution = (bin1, bin2) => {
  return (parseInt(bin1, 2) + parseInt(bin2, 2)).toString(2);
};

// 테스트
console.log(solution("10", "11"));
console.log(solution("1001", "1111"));


7. 특이사항

10진수에서 2진수로 바꾸는 방법

10진수.toString(2)

 

2진수에서 10진수로 바꾸는 방법

parseInt(2진수, 2)


8. 다른 사람이 작성한 답

8-1. 좋아요를 가장 많이 받은 풀이법

function solution(bin1, bin2) {
  let temp = Number(bin1) + Number(bin2);
  temp = [...temp.toString()].reverse().map((v) => +v);

  for (let i = temp.length; i < 11; i++) {
    temp.push(0);
  }

  for (let i = 0; i < temp.length; i++) {
    if (temp[i] === 2) {
      temp[i] = 0;
      temp[i + 1]++;
    } else if (temp[i] === 3) {
      temp[i] = 1;
      temp[i + 1]++;
    }
  }
  return Number(temp.reverse().join("")).toString();
}