CodeWars 코딩 문제 2021/03/26 - Roman Numerals Helper

이호현·2021년 3월 26일
0

Algorithm

목록 보기
95/138

[문제]

Create a RomanNumerals class that can convert a roman numeral to and from an integer value. It should follow the API demonstrated in the examples below. Multiple roman numeral values will be tested for each helper method.

Modern Roman numerals are written by expressing each digit separately starting with the left most digit and skipping any digit with a value of zero. In Roman numerals 1990 is rendered: 1000=M, 900=CM, 90=XC; resulting in MCMXC. 2008 is written as 2000=MM, 8=VIII; or MMVIII. 1666 uses each Roman symbol in descending order: MDCLXVI.

Examples

RomanNumerals.toRoman(1000); // should return 'M'
RomanNumerals.fromRoman('M'); // should return 1000

Help

Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000

(요약) 로마 숫자를 아라비아 숫자로, 아라비아 숫자를 로마 숫자로 변환해라.

[풀이]

const code = {
  I: 1,
  V: 5,
  X: 10,
  L: 50,
  C: 100,
  D: 500,
  M: 1000
}

const RomanNumerals = {
  toRoman: (num) => {
    let answer = '';
    const keys = Object.keys(code);
    let index = 0;

    while(num) {
      const dividedNum = num % 10;
      console.log(num, dividedNum)
      if(dividedNum) {
        if(dividedNum === 4) {
          answer = keys[index] + keys[index + 1] + answer;
          num -= 4;
        }
        else if(dividedNum === 5) {
          answer = keys[index + 1] + answer;
          num -= 5;
        }
        else if(dividedNum === 9) {
          answer = keys[index] + keys[index + 2] + answer;
          num -= 9;
        }
        else {
          answer = keys[index] + answer;
          num -= 1;
        }
      }
      else {
        index += 2;
        num = num / 10|0;
      }
    }

    return answer;
  },
  fromRoman: (str) => {
    let answer = 0;
 
    for(let i = 0; i < str.length; i++) {
      answer += code[str[i]] < code[str[i + 1]] ? code[str[i]] * -1 : code[str[i]];
    }

    return answer;
  }
}

로마 숫자와 아라비아 숫자를 객체로 만듦.

로마숫 자를 아라비아 숫자로 변환하는건 앞에서부터 문자를 해당하는 숫자에 맞춰 치환해서 더하고, 바로 뒤에것이 앞에거보다 크면 4나 9니까 그것만 따로 처리해 주면 됨.

아라비아 숫자를 로마 숫자로 변환할 때는 각 자리수마다 따로 계산을 해야되서 일의 자리부터 4, 5, 9, 그 외 이렇게 조건을 나눠서 문자를 추가하게 만듦.

profile
평생 개발자로 살고싶습니다

0개의 댓글