πŸ’‘ Level 1 | 숫자 λ¬Έμžμ—΄κ³Ό μ˜λ‹¨μ–΄ (JavaScript)

rimmzΒ·2022λ…„ 7μ›” 6일
0

programmers

λͺ©λ‘ 보기
14/15
post-thumbnail

πŸ“Œ 문제

λ„€μ˜€μ™€ ν”„λ‘œλ„κ°€ μˆ«μžλ†€μ΄λ₯Ό ν•˜κ³  μžˆμŠ΅λ‹ˆλ‹€. λ„€μ˜€κ°€ ν”„λ‘œλ„μ—κ²Œ 숫자λ₯Ό 건넬 λ•Œ 일뢀 자릿수λ₯Ό μ˜λ‹¨μ–΄λ‘œ λ°”κΎΌ μΉ΄λ“œλ₯Ό 건넀주면 ν”„λ‘œλ„λŠ” μ›λž˜ 숫자λ₯Ό μ°ΎλŠ” κ²Œμž„μž…λ‹ˆλ‹€.

λ‹€μŒμ€ 숫자의 일뢀 자릿수λ₯Ό μ˜λ‹¨μ–΄λ‘œ λ°”κΎΈλŠ” μ˜ˆμ‹œμž…λ‹ˆλ‹€.

  • 1478 β†’ "one4seveneight"
  • 234567 β†’ "23four5six7"
  • 10203 β†’ "1zerotwozero3"

μ΄λ ‡κ²Œ 숫자의 일뢀 μžλ¦Ώμˆ˜κ°€ μ˜λ‹¨μ–΄λ‘œ λ°”λ€Œμ–΄μ‘Œκ±°λ‚˜, ν˜Ήμ€ λ°”λ€Œμ§€ μ•Šκ³  κ·ΈλŒ€λ‘œμΈ λ¬Έμžμ—΄ sκ°€ λ§€κ°œλ³€μˆ˜λ‘œ μ£Όμ–΄μ§‘λ‹ˆλ‹€.
sκ°€ μ˜λ―Έν•˜λŠ” μ›λž˜ 숫자λ₯Ό return ν•˜λ„λ‘ solution ν•¨μˆ˜λ₯Ό μ™„μ„±ν•΄μ£Όμ„Έμš”.

참고둜 각 μˆ«μžμ— λŒ€μ‘λ˜λŠ” μ˜λ‹¨μ–΄λŠ” λ‹€μŒ ν‘œμ™€ κ°™μŠ΅λ‹ˆλ‹€.

  • 숫자 / μ˜λ‹¨μ–΄
  • 0 / zero
  • 1 / one
  • 2 / two
  • 3 / three
  • 4 / four
  • 5 / five
  • 6 / six
  • 7 / seven
  • 8 / eight
  • 9 / nine

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

πŸ“ 문제 풀이

function solution(s) {
  let answer = s;

  answer = answer.replace(/zero/gi, "0");
  answer = answer.replace(/one/gi, "1");
  answer = answer.replace(/two/gi, "2");
  answer = answer.replace(/three/gi, "3");
  answer = answer.replace(/four/gi, "4");
  answer = answer.replace(/five/gi, "5");
  answer = answer.replace(/six/gi, "6");
  answer = answer.replace(/seven/gi, "7");
  answer = answer.replace(/eight/gi, "8");
  answer = answer.replace(/nine/gi, "9");

  return Number(answer);
}
  • replace ν•¨μˆ˜λ‘œ ν•΄λ‹Ή λ¬Έμžμ—΄μ„ 숫자둜 λ³€κ²½ν•˜λ„λ‘ μž‘μ—…
  • /zero/gi μ •κ·œμ‹ : g λͺ¨λ“  λ¬Έμžμ—΄ λ³€κ²½ / i λŒ€μ†Œλ¬Έμž ꡬ별없이

🌿 λ‹€λ₯Έ μ‚¬λžŒμ˜ 풀이

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);
}
  • numbers의 λ¬Έμžμ—΄ 배열을 λ§Œλ“€κ³  ν•΄λ‹Ή 배열을 μ΄μš©ν•˜μ—¬ λ¬Έμžμ—΄ μž˜λΌλ‚Έλ‹€.
  • μž˜λΌλ‚Έ λ¬Έμžμ—΄μ— ν•΄λ‹Ή i 숫자λ₯Ό 집어넣어 λ³€κ²½ν•œλ‹€.

str.split(separator, [limit])

  • νŠΉμ • λ¬Έμžμ—΄μ„ κΈ°μ€€μœΌλ‘œ λΆ„ν• ν•˜λŠ” ν•¨μˆ˜

str.join(separator)

  • λ°°μ—΄μ˜ μš”μ†Œλ“€μ„ μ—°κ²°ν•˜μ—¬ ν•˜λ‚˜μ˜ λ¬Έμžμ—΄λ‘œ λ§Œλ“œλŠ” ν•¨μˆ˜
  • λ°°μ—΄ λ‚΄ μš”μ†Œκ°€ ν•˜λ‚˜μΌ 경우 μ—°κ²°μž 없이 λ¬Έμžμ—΄μ΄ λ°˜ν™˜
"javascript".split("j"); // ["", "avascript"]
"javascript".split("j").join(1); // 1avascript 

// λ°°μ—΄ λ‚΄ μš”μ†Œκ°€ ν•˜λ‚˜μΌ 경우 μ—°κ²°μž 없이 λ¬Έμžμ—΄μ΄ λ°˜ν™˜ μ˜ˆμ‹œ
"javascript".split("g"); // ["javascript"]
"javascript".split("g").join(1); // // javascript
profile
#μ˜μš•λ„˜μΉ˜λŠ”#πŸ’»#✨#FE#πŸ’ͺ🏻

0개의 λŒ“κΈ€