Leetcode-Roman to Integer
来源:互联网 发布:关于网络语言暴力论文 编辑:程序博客网 时间:2024/06/11 21:34
题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
题目要求,将给出的罗马数字转换为整数。
罗马数字是最早的数字表示方式,比阿拉伯数字早2000多年,起源于罗马。
如今我们最常见的罗马数字就是钟表的表盘符号:Ⅰ,Ⅱ,Ⅲ,Ⅳ(IIII),Ⅴ,Ⅵ,Ⅶ,Ⅷ,Ⅸ,Ⅹ,Ⅺ,Ⅻ……
对应阿拉伯数字(就是现在国际通用的数字),就是1,2,3,4,5,6,7,8,9,10,11,12。(注:阿拉伯数字其实是古代印度人发明的,后来由阿拉伯人传入欧洲,被欧洲人误称为阿拉伯数字。)
基本字符
I
V
X
L
C
D
M
相应的阿拉伯数字表示为
1
5
10
50
100
500
1000
1、相同的数字连写,所表示的数等于这些数字相加得到的数,如:Ⅲ = 3;
2、小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数, 如:Ⅷ = 8;Ⅻ = 12;
3、小的数字,(限于Ⅰ、X 和C)在大的数字的左边,所表示的数等于大数减小数得到的数,如:Ⅳ= 4;Ⅸ= 9;
4、正常使用时,连写的数字重复不得超过三次。(表盘上的四点钟“IIII”例外)
5、在一个数的上面画一条横线,表示这个数扩大1000倍。
有几条须注意掌握:
1、基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。
2、不能把基本数字V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。
3、V 和X 左边的小数字只能用Ⅰ。
4、L 和C 左边的小数字只能用X。
5、D 和M 左边的小数字只能用C。
以上罗马数字的内容,来自:http://www.cnblogs.com/grandyang/p/4120857.html
搞清楚规则后,就可以直接写代码啦。
//Roman to Integer class Solution {public: int romanToInt(string s) { int r = 0; r = r + toNum(s[0]); for(int i = 0; i < s.size()-1; i++) { int a = toNum(s[i]); int b = toNum(s[i+1]); if(a < b) { r = r + b - 2*a; } else { r = r + b; } } return r; } int toNum(char a) { switch(a) { 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; } return 0; }};
阅读全文
0 0
- LeetCode Roman to Integer && Integer to Roman
- 【leetcode】Roman to Integer | Integer to Roman
- Leetcode - "Roman to Integer" & "Integer to Roman"
- LeetCode:Roman to Integer,Integer to Roman
- LeetCode Integer to Roman & Roman to Integer
- leetcode - roman to integer & integer to roman
- LeetCode:Roman to Integer
- LeetCode: Integer to Roman
- LeetCode: Roman to Integer
- LeetCode Integer to Roman
- LeetCode: Integer to Roman
- LeetCode : Roman to Integer
- [Leetcode] Roman to Integer
- [Leetcode] Integer to Roman
- Leetcode: Integer to Roman
- Leetcode: Roman to Integer
- LeetCode Integer to Roman
- 【leetcode】Roman to Integer
- 学习
- 99乘法
- java数据结构中队列的使用
- python:10:错误与异常
- 网易2018校招编程题5
- Leetcode-Roman to Integer
- Vmware12安装CentOS7,如何设置host-only模式下的静态ip
- 进程学习:进程间通信(传统通信方式)3.信号
- TCP与UDP协议的区别
- git 命令大全
- 浪漫的漫天爱心01(java)
- javascript介绍及如何在html中使用js与jQuery
- 中国程序员如何升职加薪,也许我们该学学印度人
- android7.0打电话是否是紧急号码