[leetcode] 【字符串】13. Roman to Integer

来源:互联网 发布:小田切让演技知乎 编辑:程序博客网 时间:2024/06/16 11:25

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

题意

把罗马数字转变为int型数据

题解

转变的规则      :

//Ⅰ(1)Ⅴ(5)Ⅹ(10)L(50)C(100)D(500)M(1000) 

  1. 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;
  2. 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12;
  3. 小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9;
根据这个规则去一一遍历即可。
class Solution {public:    int romanToInt(string s) {        int len=s.size();        int roman[len]={0};        int romantotle=0;        for(int i=len-1;i>=0;i--)        {            switch(s[i])            {                case 'I':   roman[i]=1;                    break;                case 'V':   roman[i]=5;                    break;                case 'X':   roman[i]=10;                    break;                case 'L':   roman[i]=50;                    break;                case 'C':   roman[i]=100;                    break;                case 'D':   roman[i]=500;                    break;                case 'M':   roman[i]=1000;                    break;                default:    break;            }            if(roman[i]<roman[i+1]&&i<len-1)                roman[i]=-roman[i];            romantotle+=roman[i];        }        return romantotle;    }};


0 0
原创粉丝点击