LeetCode: Roman to Integer
来源:互联网 发布:网络暴力 违法 知乎 编辑:程序博客网 时间:2024/05/03 18:16
题目:
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
题目给定一个字符组成的罗马数字,要求把这个罗马数字转化为整数。
答题之前,需要先了解一下罗马数字的表示:
在罗马数字中,I,V,X,L,C,D,M分别表示阿拉伯数字的1,5,10,50,100,500,1000。相同的字符连写,所表示的数等于这些字符对应的数字相加得到的数,如:Ⅲ = 3;对应的数字小的字符在对应的数字大的字符右边,所表示的数等于字符对应的数字相加得到的结果, 如:Ⅷ = 8;Ⅻ = 12;对应的数字小的字符在对应的数字大的字符左边,所表示的数等于大数减小数得到的结果,如:Ⅳ= 4;Ⅸ= 9;一般不能有超过三个的数字连写。
由于这些表示数字的字符的ASCII码不是随着所表示的数字的增大而增大的,所以,为了方便比较,先把字符串内的所有字符依次转化为整数保存在数组中,比较时遍历数组即可。
算法:
从前往后遍历数组,用一个临时变量记录分段结果,临时变量初始化为第一个元素,从第二个元素开始遍历。如果:
1. 当前元素等于上一个元素,把当前元素加到临时变量中。
2. 当前元素大于上一个元素,把临时变量的相反数加到结果中,并更新临时变量为当前元素。
3. 当前元素小于上一个元素,把临时变量加到结果中,并更新临时变量为当前元素。
遍历完数组后,返回结果值与临时变量的和。
只需要对数组从头往后遍历一次,算法的复杂度为o(n),n为罗马数字的字符数。
Accepted的代码:
class Solution {public: int romanToInt(string s) { //将罗马数字中的字符转化为整数 vector<int> temp; for(int i=0;i<s.length();i++) { if(s[i]=='M') temp.push_back(1000); else if(s[i]=='D') temp.push_back(500); else if(s[i]=='C') temp.push_back(100); else if(s[i]=='L') temp.push_back(50); else if(s[i]=='X') temp.push_back(10); else if(s[i]=='V') temp.push_back(5); else if(s[i]=='I') temp.push_back(1); else temp.push_back(0); } //计算结果 int result=0; int count=temp[0];//临时变量 //int index=0; for(int i=1;i<temp.size();i++) { //当前元素等于上一个元素 if(temp[i]==temp[i-1]) count+=temp[i]; //当前元素大于上一个元素 else if(temp[i]>temp[i-1]) { result-=count; count=temp[i]; } //当前元素小于上一个元素 else { result+=count; count=temp[i]; } } return result+count; }};
- 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
- CODEVS 1154能量项链
- 关于MyEclipse启动Tomcat,程序能运行,startup.bat启动,Tomcat启动成功,但程序不运行的问题
- 监听Android应用前后台运行状态
- 《网络、群体与市场》概况
- 《CLR via C#》读书笔记-.NET多线程(三)
- LeetCode: Roman to Integer
- 【NMF】用python实现非负矩阵分解
- Hopcroft-Harp 算法
- 工作流——这是个什么鬼?
- 姿态解算系列一:经验型卡尔曼数据融合
- Struts2学习笔记(6)
- linux挂载的简单使用
- opencv floodFill 漫水填充
- Chart.Js轻量级HTML5图表插件