Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Roman Numeral Value

Convert a Roman numeral to a number.

Bạn sẽ học được gì

  • Map symbols to values with a dictionary
  • Handle subtractive pairs like IV and XC
  • Scan a string while looking at the next character

Đề bài

Xem bản dịch

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ụ

Ví dụ 1
Đầ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.

Ví dụ 2
Đầ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.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.