문제(출처: 프로그래머스)

문자열 my_string이 매개변수로 주어집니다. my_string안의 모든 자연수들의 합을 return하도록 solution 함수를 완성해주세요.

 

▶ 내가 푼 방식

//내가 작성한 코드
function solution(my_string) {
    const numbers = my_string.replace(/\D/g, '');
    const numberArray = [...numbers].map(Number)
    const answer = numberArray.reduce((a,b) => a+ b, 0) 
    return answer;
}

 

 다른 유저가 푼 방식

// 유저 1
function solution(my_string) {
    const answer = my_string.replace(/[^0-9]/g, '')
                            .split('')
                            .reduce((acc, curr) => acc + Number(curr), 0);
    return answer;
}

// 유저 2
function solution(my_string) {
    let sum = 0;
    for (const ch of my_string) {
        if (!isNaN(ch)) sum += +ch;
    }
    return sum;
}

 

 배운 것들

     -  숫자로 시작하지 않는  문자를 찾는  정규 표현식 /[^0-9]/g

     - array.reduce((accumulator, currentValue) => 원하는계산, initialValue)

+ Recent posts