본문 바로가기
코딩테스트(알고리즘)/프로그래머스

[프로그래머스] 숫자 문자열과 영단어 (Javascript)

by Cafe Mocha 2022. 6. 23.

코딩테스트 연습 - 숫자 문자열과 영단어 | 프로그래머스 (programmers.co.kr)

 

코딩테스트 연습 - 숫자 문자열과 영단어

네오와 프로도가 숫자놀이를 하고 있습니다. 네오가 프로도에게 숫자를 건넬 때 일부 자릿수를 영단어로 바꾼 카드를 건네주면 프로도는 원래 숫자를 찾는 게임입니다. 다음은 숫자의 일부 자

programmers.co.kr


접근 : 구현

1. numbers에 문자열과 index번호로 정렬

2. numbers를 forEach로 돌면서 모든 문자열을 숫자로 변경

3. indexOf()와 splice로 치환

 

Javascript

function solution(s) {
    let answer = "";
    let numbers = ["zero","one","two","three","four","five","six","seven","eight","nine"];
    numbers.forEach((num,idx)=>{
        while(s.indexOf(num)!==-1){
            let indx = s.indexOf(num);
            s=s.split("");
            s.splice(indx,num.length,idx);
            s= s.join("");
        }
    })
    
    answer = Number(s);
    
    
    return answer;
}