leetcode 13 Roman to Integer
来源:互联网 发布:在淘宝上如何开虚拟店 编辑:程序博客网 时间:2024/05/17 06:16
题目:
Given a roman numeral, convert it to an integer . Input is guaranteed to be within the range from 1 to 3999.
将罗马数字转译为阿拉伯数字。
思路:
基本字符相应的阿拉伯数字: I(1)、V(5)、X(10)、L(50)、C(100)、D(500)、M(1000)
(1)相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
(2)小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
(3)小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
(4)正常使用时,连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外)
组数规则(本次转译并没有检查罗马数字的正确性,只按照相应的数字转译而已)
(1)基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。
(2)不能把基本数字V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。
(3)V 和X 左边的小数字只能用Ⅰ。
(4)L 和C 左边的小数字只能用X。
(5)D 和M 左边的小数字只能用C。
函数方法:
例如:MCMXCVI, 比较MC(M代表的1000大于C的100,sum加上1000;)
比较CM(100小于1000,sum减去100)
比较MX(1000大于10,sum加上1000)依此类推
int romanToInt(char* s) { int len=strlen(s);//字符串长度 int i; int a[256];//每个罗马字符对应的数字 a['I']=1 , a['V']=5 , a['X']=10 , a['L']=50 , a['C']=100 , a['D']=500 , a['M']=1000; int sum=0;//返回的阿拉伯数值 int tem1,tem2; for(i=0;i<len;i++)//每次比较两个罗马字符,左边小于右边的,减去左边的数值,否则加上左边的数值, { if(i+1<len) { tem1=a[s[i]]; tem2=a[s[i+1]]; } else { tem1=a[s[i]]; tem2=1; } if(tem1>=tem2) { sum=sum+tem1; } else { sum=sum-tem1; } } return sum;}
- leetcode-13:Roman to Integer
- leetcode 13 Roman to Integer
- Leetcode【13】:Roman to Integer
- [leetcode 13] Roman to Integer
- [Leetcode] 13 - Roman to Integer
- LeetCode | #13 Roman to Integer
- leetcode.13---------Roman to Integer
- leetCode #13 Roman to Integer
- leetcode-13 Roman to Integer
- leetcode 13 Roman to Integer
- LeetCode 13 Roman to Integer
- LeetCode 13 - Roman to Integer
- leetcode 13 -- Roman to Integer
- LeetCode 13:"Roman to Integer"
- LeetCode---(13)Roman to Integer
- leetcode-13Roman to Integer
- leetcode 13: Roman to Integer
- Leetcode 13 Roman to Integer
- 文件指针权限
- c语言函数的秘密
- linux window mac ox sqlite安装
- C++中define与const的区别
- PostgreSQL之树形展示
- leetcode 13 Roman to Integer
- ArcGIS许可服务管理器无法启动问题
- 关于latex简历几个非常有用的命令
- Mac OS X EL Capitan 与office不兼容!升级要谨慎
- static_cast 的用法
- 区间调度问题
- 接口和抽象类有什么区别
- GPU简述
- 源码分析shiro认证授权流程