ง่าย 1 ข้อที่แก้แล้ว อัตราผ่าน 100.0%

Roman Numeral Value

Convert a Roman numeral to a number.

สิ่งที่คุณจะได้เรียนรู้

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

โจทย์

ดูฉบับแปล

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

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
text = "XIV"

ผลลัพธ์ที่คาดหวัง:
expected = 14
อินพุต:
std::string text = "XIV";

ผลลัพธ์ที่คาดหวัง:
long long expected = 14;
อินพุต:
string text = "XIV";

ผลลัพธ์ที่คาดหวัง:
long expected = 14;

คำอธิบาย

X = 10, IV = 4: 14.

ตัวอย่างที่ 2
อินพุต:
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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

# นักโค้ด ภาษา เวลา หน่วยความจำ คะแนนจาก AI คำตอบ
1 HJhettory Jurash Python 807 ms - 3/5 ดูโค้ด

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

สปอยล์: มีคำตอบเต็ม 1 ข้อด้านล่าง ลองแก้ด้วยตัวเองก่อน คุณยังสามารถดูโค้ดของนักพัฒนาคนอื่นและรีวิว AI ได้ เข้าสู่ระบบและแก้โจทย์เพื่อร่วมพูดคุย