banner
ekko

ekko's blog

时间不在于你拥有多少,而在于你怎样使用
github
xbox
email

Roman Numerals to Integer

Description#

Roman numerals are represented by seven different symbols: I, V, X, L, C, D, and M.

Symbol       Value
I             1
V             5
X             10
L             50
C             100
D             500
M             1000

For example, two is written as II in Roman numeral, just two one's added together. Twelve is written as XII, which is simply X + II. The number twenty-seven is written as XXVII, which is XX + V + II.

Roman numerals are usually written largest to smallest from left to right. However, the numeral for four is not IIII. Instead, the number four is written as IV. Because the one is before the five we subtract it making four. The same principle applies to the number nine, which is written as IX. 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 numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.

Example 1:

Input: "III"
Output: 3

Example 2:

Input: "IV"
Output: 4

Example 3:

Input: "IX"
Output: 9

Example 4:

Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.

Example 5:

Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90, IV = 4.

Approach#

  • Start from the first character of the string. If the value of the current character is not less than the value of the next character, add the value of the current character to the result. Otherwise, subtract the value of the current character from the result.
  • Simplify the mapping of each letter to its corresponding value using an array based on the ASCII values of these seven letters. This can be achieved by using the hexadecimal representation of each ASCII value and performing a bitwise AND operation with 0xF to obtain a unique key for each character.
int romanToInt(char * s){
    int nums[15] = {0};
                    //Decimal: Hexadecimal: Binary
    nums[9]  = 1;   //I:73:0X49:1001
    nums[6]  = 5;   //V:86:0X56:0110
    nums[8]  = 10;  //X:88:0X58:1000
    nums[12] = 50;  //L:76:0X4C:1011
    nums[3]  = 100; //C:67:0X43:0011
    nums[4]  = 500; //D:68:0X44:0100
    nums[13] = 1000;//M:77:0X4D:1101
    for(unsigned char i = 0;s[i] != '\0';i++) {
        if(nums[s[i] & 0xf] >= nums[s[i+1] & 0xf])
            nums[1] += nums[s[i] & 0xf];
        else
            nums[1] -= nums[s[i] & 0xf];
    }
    return nums[1];
}

Note#

  • Only subtract the current value when the value of the next character is less than the value of the current character.
Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.