Oct-08-2018
争取每周做五个LeedCode题,定期更新,难度由简到难
Title: Roman 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:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
Example
Input: "III"
Output: 3
Input: "IV"
Output: 4
Input: "IX"
Output: 9
Input: "LVIII"
Output: 58
Explanation: L = 50, V= 5, III = 3.
Input: "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
Difficulty:
Easy
Implement Programming Language:
C#
Answer:
这道题就是把罗马数字转换成为我们用的int值。IV这种,I会在V的基础上减一,就是4,我们需要单独处理。
public static int RomanToInt(string value)
{
int result = 0;
for (int i = value.Length - 1; i >=0; i--)
{
char t = value[i];
switch (t)
{
case 'I':
result += result >= 5 ? -1 : 1;
break;
case 'V':
result += 5;
break;
case 'X':
result += result >= 50 ? -10 : 10;
break;
case 'L':
result += 50;
break;
case 'C':
result += result >= 500 ? -100 : 100;
break;
case 'D':
result += 500;
break;
case 'M':
result += 1000;
break;
}
}
return result;
}
简单解释一下,刚看题的思路,就是读取字符串,然后匹配关键字取值。比如IV对应4这样,但是逻辑比较乱。
其实反过来读,例如像IV这种,读到I的时候,结果已经是4了,不可能小的数字在大的数字前面,所以是做减数的,这样就有上面的代码了。