Đề bài
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.
Ràng buộc
1 ≤ value ≤ 3,999
Ví dụ
Đầu vào:
text = "XIV"
Kết quả mong đợi:
expected = 14
Đầu vào:
std::string text = "XIV";
Kết quả mong đợi:
long long expected = 14;
Đầu vào:
string text = "XIV";
Kết quả mong đợi:
long expected = 14;
Giải thích
X = 10, IV = 4: 14.
Đầu vào:
text = "MCMXCIV"
Kết quả mong đợi:
expected = 1994
Đầu vào:
std::string text = "MCMXCIV";
Kết quả mong đợi:
long long expected = 1994;
Đầu vào:
string text = "MCMXCIV";
Kết quả mong đợi:
long expected = 1994;
Giải thích
M=1000, CM=900, XC=90, IV=4: 1994.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Most symbols add their value, but some pairs subtract when a smaller symbol appears before a larger one.
Gợi ý 2
Process the numeral from left to right and compare each symbol with the next one.
Gợi ý 3
Make sure the last symbol is always handled correctly since it has no follower.
Độ phức tạp mong đợi
O(n) time, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.