更新时间:2022-08-25 17:21:28
Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.
首先简单介绍一下罗马数字,一下摘自***
罗马数字共有7个,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。按照下述的规则可以表示任意正整数。需要注意的是罗马数字中没有“0”,与进位制无关。一般认为罗马数字只用来记数,而不作演算。
3999范围内的罗马数字不会用到加上划线的字母
从第一个字符开始,如果当前字符对应的数字比后一个数字小,那么就把结果减去当前字符对应的数字,否则加上当前字符对应数字。为了处理边界情况(最后一个字符需要加入),在原字符串最后添加一个字符,该字符是原来的尾字符(两个字符相等,所以最后一个字符始终是加入)。
C++实现代码:
#include<iostream> #include<string> using namespace std; class Solution { public: int romanToInt(string s) { int map[26]; map['I'-'A']=1; map['V'-'A']=5; map['X'-'A']=10; map['L'-'A']=50; map['C'-'A']=100; map['D'-'A']=500; map['M'-'A']=1000; int i; int res=0; s.push_back(s[s.length()-1]); for(i=0;i<s.length()-1;i++) { if(map[s[i]-'A']>=map[s[i+1]-'A']) res+=map[s[i]-'A']; else res-=map[s[i]-'A']; } return res; } }; int main() { Solution s; cout<<s.romanToInt("IVVII")<<endl; }