本文共 4605 字,大约阅读时间需要 15 分钟。
Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.
罗马数字是用七个不同的标志表示:I, V, X, L, C, D 和M.
Symbol ValueI 1V 5X 10L 50C 100D 500M 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.
例如:2在罗马数字中使用II表示,仅仅是两个1相加。12写作XII,仅仅是X和II相加。27写作XXVII,就是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:
罗马数字常常是由左到右,按照最大到最小的方式去写的。然而,数字4并不是IIII。而是,数字4写为IV。因为1在左边表示减去1,5减1,就是4.同样的原则也适用于9,写作IX。下面有六个使用减法的例子。
* 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.
给你一个罗马数字,将之转化成整型数字。输入的数字是在1至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 and IV = 4.
#include#include #include int romanToInt(char *s);int main(){ //今日分leetcode char *p = "LVIII"; printf("%d \n",romanToInt(p)); return 0;}/* 功能描述:将罗马字符串转成对应的数字*/int romanToInt(char *s){ int result = 0; while(*s) { switch (*s) { case 'I': if(*(s + 1) && *(s + 1) == 'V') { result += 4; s ++ ; } else if(*(s + 1) && *(s + 1) == 'X') { result += 9; s ++; } else { result += 1; } break; case 'V': result += 5; break; case 'X': if(*(s + 1) && *(s + 1) == 'L') { result += 40; s ++ ; } else if(*(s + 1) && *(s + 1) == 'C') { result += 90; s ++; } else { result += 10; } break; case 'L': result += 50; break; case 'C': if(*(s + 1) && *(s + 1) == 'D') { result += 400; s ++ ; } else if(*(s + 1) && *(s + 1) == 'M') { result += 900; s ++; } else { result += 100; } break; case 'D': result += 500; break; case 'M': result += 1000; break; default: break; } s ++; } return result;}
int romanToInt(char *s){ int left = 0,right = 0; int result = 0; while(*s) { left = ConvertToNumber(s); right = ConvertToNumber(s+1); if(left >= right) { result += left; } else { result = result + right - left; s ++; } s ++; } return result;}int ConvertToNumber(char *s){ switch (*s) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: return 0; }}
转载地址:http://oggpb.baihongyu.com/