알고리즘🅰/리트코드
[리트코드] 13. Roman to Integer
개발조각
2022. 9. 13. 23:17
728x90
반응형
안녕하세요. 개발조각입니다.😊
이번에는 12번문제의 반대 버전이에요. 확실히 easy이다 보니 쉽더라고요.
https://leetcode.com/problems/roman-to-integer/
Roman to Integer - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
해결방안
var romanToInt = function(s) {
let roma = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000};
let num = 0;
for(let i=0; i<s.length; i++){
let current = roma[s[i]];
let next = roma[s[i+1]];
if(current < next){
num -= current;
}else num += current;
}
return num;
};
이문제의 해결방안에 대해 설명하자면
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
이러한 예제가 있으면
'MCMXCIV'를 각 문자단위로 숫자로 바꾸면
'1000, 100, 1000, 10, 100, 1, 5' 이렇게 됩니다.
이걸 보시면 규칙이 보이실 거예요.
1000 + (1000-100) + (100-10) + (5-1) = 1994
이렇게 현재 숫자 < 다음 숫자 이러면 다음 숫자-현재 숫자를 하면 됩니다.
이걸 좀 더 간단하게 하면
- 현재 숫자 < 다음 숫자 → -현재 숫자
- 현재 숫자 < 다음 숫자 아니면 → +현재 숫자
이렇게 해주면 됩니다.
728x90
반응형