본문 바로가기
Javascript/코딩테스트-연습

[JavaScript] 숫자의 덧셈(2) - 프로그래머스

by BeomBe 2024. 4. 9.
반응형

이제 입문은 7개 남았다...

 

이후에는 코딩테스트 포스팅은 줄이고, 포스팅 갯수는 줄더라도 좀 더 핵심이 될만한 내용들을 포스팅 하려고 한다.

 

문제 설명

 

문제 설명을 더 자세히 보고싶은 분은 아래의 링크를 참고하여 주세요.

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

 

프로그래머스

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

programmers.co.kr

 

나의 풀이

정규표현식을 통해서 String 안에서 숫자를 구분하고, map과 reduce를 이용해서 배열 요소를 반환하면 된다.

function solution(my_string) {
    let answer = my_string.match(/[0-9]+/g);
    
    return answer ? answer.map(num => Number(num))
                      .reduce( (a, c) => a + c, 0) : 0;
}

 

다른사람의 풀이

function solution(my_string) {
  return my_string.split(/\D+/).reduce((acc, cur) => acc + Number(cur), 0);
}

 

정규 표현식에서 확인해봤을때 \D에 대해 설명을 하면,

\D :: Matches any character that is not a digit (Arabic numeral). Equivalent to [^0-9]. For example, /\D/ or /[^0-9]/ matches "B" in "B2 is the suite number".

숫자(아라비아 숫자)가 아닌 모든 문자와 일치합니다. [^0-9]와 동일합니다. 예를 들어 /\D/ 또는 /[^0-9]/는 "B2가 모음 번호입니다"의 "B"와 일치합니다.

 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_expressions/Character_classes

 

Character classes - JavaScript | MDN

Character classes distinguish kinds of characters such as, for example, distinguishing between letters and digits.

developer.mozilla.org

 

반응형