๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

ํ”„์—” ๊ณต๋ถ€/๐Ÿซง ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€

[์•Œ๊ณ ๋ฆฌ์ฆ˜ || ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ˆซ์ž ๋ฌธ์ž์—ด๊ณผ ์˜๋‹จ์–ด

728x90

ํ’€๋ฉด์„œ ์ •๋ฆฌ๋ฅผ ์•ˆํ–ˆ๋”๋‹ˆ ๋”์šฑ ๊นŒ๋จน๋Š” ๋Š๋‚Œ์ด ๋“œ๋„ค. 

์š”์ฆ˜์€ ๋ฆฌ์•กํŠธ ์ฑŒ๋ฆฐ์ง€ ํ•˜๋Š๋ผ ๋„ˆ๋ฌด ์‹œ๊ฐ„์ด ๋ถ€์กฑํ•œ ๋Š๋‚Œ์ด๋‹ค. 

๋ญ, ๊ณ„ํšํ•œ ๊ฑธ ๋‹ค ์ง€ํ‚ค์ง€ ๋ชปํ•ด๋„ ํ•˜๋ฃจ๋ฅผ ๊ฝ‰๊ฝ‰ ์ฑ„์›Œ์„œ ์—ด์‹ฌํžˆ ํ•ด๋ณด์ž. 

 

function solution(s) {
    const numChart = {
        "zero": 0,
        "one": 1,
        "two": 2,
        "three": 3,
        "four": 4,
        "five": 5,
        "six": 6,
        "seven": 7,
        "eight": 8,
        "nine": 9
    }
    let word = '';
    return Number([...s].map(char => {
        if (char == Number(char)) {
            return char;
        } else {
            word += char;
            const number = numChart[word];
            if (number || number === 0) {
                word = "";
                return number
            }
        }
    }).join(""))
}

์ด๋ ‡๊ฒŒ word ๋ฅผ ๋งŒ๋“ค์–ด์„œ object ์˜ key ๊ฐ’์œผ๋กœ value ๊ฐ€ ์กด์žฌํ•œ๋‹ค๋ฉด return์„ ํ•ด์ค€ ํ›„, join์œผ๋กœ ํ•˜๋‚˜์˜ ๋ฌธ์ž์—ด์„ ๋งŒ๋“ค์–ด์ค€๋‹ค. ๊ทธ๋ฆฌ๊ณ  return ๊ฐ’์ด number ์—ฌ์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ์— Number ํ•จ์ˆ˜๋กœ ๊ฐ์‹ธ์คฌ๋‹ค. value ๊ฐ’์ด ์กด์žฌํ•˜๋Š”์ง€ ํ™•์ธ ํ•  ๋•Œ 0์ด๋ผ๋ฉด falsy ๊ฐ’์œผ๋กœ ์ธ์‹ํ•  ์ˆ˜ ์žˆ์œผ๋‹ˆ, ์กด์žฌํ•˜๊ฑฐ๋‚˜, ๊ฐ’์ด 0์ธ ๊ฒฝ์šฐ๋ฅผ ๋”ฐ๋กœ ์จ์คฌ๋‹ค. 

 

 

์˜ค๋Š˜๋„ ์—ญ์‹œ๋‚˜ ๊ณ ์ˆ˜๋“ค์˜ ๋‹ต๋ณ€์—์„œ ์ข‹์€ ๋ฐฉ๋ฒ•๋“ค์„ ๋งŽ์ด ๋ฐœ๊ฒฌํ–ˆ๋‹ค. 

function solution(s) {
    let numbers = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
    var answer = s;

    for(let i=0; i< numbers.length; i++) {
        let arr = answer.split(numbers[i]);
        answer = arr.join(i);
    }

    return Number(answer);
}

 

 

zero [ 'one4seveneight' ]
one [ '', '4seveneight' ]
two [ '14seveneight' ]
three [ '14seveneight' ]
four [ '14seveneight' ]
five [ '14seveneight' ]
six [ '14seveneight' ]
seven [ '14', 'eight' ]
eight [ '147', '' ]
nine [ '1478' ]
1478โ€‹

์ด๋ ‡๊ฒŒ ํ•ด๋‹นํ•˜๋Š” ์ˆซ์ž์˜ ์˜์–ด๊ฐ€ ๋‚˜์˜ฌ ๋•Œ๋งŒ ๊ทธ ๋‹จ์–ด๋ฅผ ๊ธฐ์ค€์œผ๋กœ split ์ด ๋˜๋‹ˆ๊นŒ, ์‚ฌ๋ผ์ง€๊ณ , ๊ทธ ์ˆซ์ž๋ฅผ return ํ•  answer ์— ์ฐจ๊ณก์ฐจ๊ณก ๋ถ™์ผ ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค. 

split ์„ ์ด๋Ÿฐ ์‹์œผ๋กœ ๊ต์ฒดํ•  ๋•Œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ๋„ ๊ธฐ์–ตํ•˜์ž..!

 

728x90
๋ฐ˜์‘ํ˜•