Data Structure & Algorithm: Level-1 Problem #23. Roman Numerals

Roman numerals are a numeral system that originated in ancient Rome and remained the usual way of writing numbers throughout Europe well into the Late Middle Ages. Numbers in this system are represented by combinations of letters from the Latin alphabet. Modern usage employs seven symbols, each with a fixed integer value:

SymbolIVXLCDM
Value1510501005001000

One place they are often seen is on clock faces. For instance, on the clock of Big Ben (designed in 1852), the hours from 1 to 12 are written as:

I, II, III, IV, V, VI, VII, VIII, IX, X, XI, XII

The notations IV and IX can be read as ‘one less than five’ (4) and ‘one less than ten’ (9). There are six instances where subtraction is used:

  • I can be placed before V (5) and X (10) to make 4 and 9. 
  • X can be placed before L (50) and C (100) to make 40 and 90. 
  • C can be placed before D (500) and M (1000) to make 400 and 900.

Given a roman number, convert it to base-10 integer.

Sample Input: MDCCLXXVI

Sample Output: 1776

1776 = M + DCC + LXX + VI = MDCCLXXVI (the date written on the book held by the Statue of Liberty).


数据结构和算法:初级练习题 #23 – 罗马数字


罗马数字是一种起源于古罗马的数字系统,在整个欧洲一直沿用到中世纪晚期。这个系统中的数字由拉丁字母表中的字母组合来表示。现代用法使用七个符号,每个符号都有一个固定的整数值:

符号IVXLCDM
数值1510501005001000

罗马数字经常出现在时钟上。例如,1852年设计的英国伦敦大本钟上,1点到12点记为:

I, II, III, IV, V, VI, VII, VIII, IX, X, XI, XII

符号IV和IX分别表示“五减一”(4)和“十减一”(9)。这样使用减法的情况有六种:

  • I 位于 V (5) 和 X (10) 之前表示 4 和 9. 
  • X 位于 L (50) 和 C (100) 之前表示 40 和 90. 
  • C 位于  D (500) 和 M (1000) 之前表示 400 和 900.

给定一个罗马数字,把它转换为十进制数字。

输入样例:MDCCLXXVI

输出样例:1776

1776 = M + DCC + LXX + VI = MDCCLXXVI 


Python Solution

Roman Numerals