Roman numerals are represented by seven different symbols:
I, V, X, L, C, D and M.
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
For example, two is written as II in Roman numeral, just two one's added together.
Twelve is written as, XII, which is simply X + II.
The number twenty seven is written as XXVII, which is XX + V + II.
Roman numerals are usually written largest to smallest from left to right.
However, the numeral for four is not IIII. Instead, the number four is written as IV.
Because the one is before the five we subtract it making four.
The same principle applies to the number nine,
which is written as IX. There are six instances where subtraction is used:
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900.
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
Example 1:
Input: "III"
Output: 3
Example 2:
Input: "IV"
Output: 4
Example 3:
Input: "IX"
Output: 9
Example 4:
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Example 5:
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
var romanToInt = function(s) {
};
로마숫자를 숫자로 변환하라는 문제인데,
주의할 곳은 중간에 있는 IV, IX, XL, XC 뭐 이런것들이다.
로마숫자 자체가 좀 생소한데 주어진 범위가 4000까지밖에 안되어서
좀 야매로 푼 느낌이 없지 않다.
var romanToInt = function(s) {
let resultSum = 0;
let roman = {
I:1,
V:5,
X:10,
L:50,
C:100,
D:500,
M:1000,
}
let exception = { //이 부분을 자동화 할수 있는 방법을 생각해봤는데
IV : 4, //딱히 생각이 나지 않았고, 숫자의 범위가 작아서
IX : 9, //그냥 이렇게 따로 변수로 선언해주었다.
XL : 40,
XC : 90,
CD : 400,
CM : 900
}
for(let i=0; i<s.length; i++){
let stringOfException = s[i]+s[i+1] //예외문자는 이렇게 붙어서 나온다
if(exception[stringOfException]){
resultSum = resultSum + exception[stringOfException]
i = i + 1 //이 부분에서 i를 올려주지 않는다면 else가 실행된다.
console.log("first",i)
} else {
resultSum = resultSum + roman[s[i]]
console.log("second",i)
}
}
return resultSum
};
i를 올려주지 않았더니 if 와 else가 둘다 실행되어 resultSum이 원하는 숫자가
나오지 않았었다.
그 이유를 찾는데서 좀 시간을 낭비했다.