ํ๋ฉด์ ์ ๋ฆฌ๋ฅผ ์ํ๋๋ ๋์ฑ ๊น๋จน๋ ๋๋์ด ๋๋ค.
์์ฆ์ ๋ฆฌ์กํธ ์ฑ๋ฆฐ์ง ํ๋๋ผ ๋๋ฌด ์๊ฐ์ด ๋ถ์กฑํ ๋๋์ด๋ค.
๋ญ, ๊ณํํ ๊ฑธ ๋ค ์งํค์ง ๋ชปํด๋ ํ๋ฃจ๋ฅผ ๊ฝ๊ฝ ์ฑ์์ ์ด์ฌํ ํด๋ณด์.
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 ์ ์ด๋ฐ ์์ผ๋ก ๊ต์ฒดํ ๋ ์ฌ์ฉํ ์ ์๋ค๋ ๊ฒ๋ ๊ธฐ์ตํ์..!
'ํ์ ๊ณต๋ถ > ๐ซง ์๊ณ ๋ฆฌ์ฆ ๊ณต๋ถ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์๊ณ ๋ฆฌ์ฆ || ๋ฐฑ์ค JS] 1676 ํฉํ ๋ฆฌ์ผ 0์ ๊ฐ์ (1) | 2023.10.17 |
---|---|
[์๊ณ ๋ฆฌ์ฆ || ๋ฐฑ์ค] 10250 ACM ํธํ JS (1) | 2023.10.06 |
[์๊ณ ๋ฆฌ์ฆ || ํ๋ก๊ทธ๋๋จธ์ค] 3์ง๋ฒ ๋ค์ง๊ธฐ (0) | 2023.09.12 |
[์๊ณ ๋ฆฌ์ฆ || ํ๋ก๊ทธ๋๋จธ์ค] ์ต๋๊ณต์ฝ์์ ์ต์๊ณต๋ฐฐ์ (0) | 2023.09.09 |
[์๊ณ ๋ฆฌ์ฆ || ํ๋ก๊ทธ๋๋จธ์ค] ์ง์ฌ๊ฐํ ๋ณ์ฐ๊ธฐ - String.repeat() (0) | 2023.09.09 |