문제
Convert a valid Roman numeral to its value. Symbols are I=1, V=5, X=10, L=50, C=100, D=500, M=1000; a smaller symbol before a larger one is subtracted (IV = 4, CM = 900).
Implement roman_to_int(text).
Input
text: A valid Roman numeral.
Output
Return its value.
제약 조건
1 ≤ value ≤ 3,999
예시
입력:
text = "XIV"
예상 출력:
expected = 14
입력:
std::string text = "XIV";
예상 출력:
long long expected = 14;
입력:
string text = "XIV";
예상 출력:
long expected = 14;
설명
X = 10, IV = 4: 14.
입력:
text = "MCMXCIV"
예상 출력:
expected = 1994
입력:
std::string text = "MCMXCIV";
예상 출력:
long long expected = 1994;
입력:
string text = "MCMXCIV";
예상 출력:
long expected = 1994;
설명
M=1000, CM=900, XC=90, IV=4: 1994.
접근 방법
먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.
힌트 1
Most symbols add their value, but some pairs subtract when a smaller symbol appears before a larger one.
힌트 2
Process the numeral from left to right and compare each symbol with the next one.
힌트 3
Make sure the last symbol is always handled correctly since it has no follower.
예상 복잡도
O(n) time, O(1) extra space
참고 자료
이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.