LeetCode - Roman to Integer

来源:互联网 发布:陈克礼枪毙 知乎 编辑:程序博客网 时间:2024/06/05 03:28

题目描述:

Given a roman numeral, convert it to an integer.

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

本题较简单,我采用的方法是从字符串第一位开始进行识别并确定其代表的数值大小后加入integer,根据罗马数字表示规则,进行分类讨论,识别完后将字符删去。


class Solution {public:    int romanToInt(string s) {int num=0;        while(s[0]=='M')        {        num+=1000;        s.erase(0,1);        }                if(s[0]=='C'&&s[1]=='D')        {        num+=400;        s.erase(0,2);        }        else while(s[0]=='C'||s[0]=='D'||s[0]=='M')        {        if(s[0]=='C')   num+=100;        else if(s[0]=='D')  num+=500;        else if(s[0]=='M')  num+=800;        s.erase(0,1);        }                if(s[0]=='X'&&s[1]=='L')        {        num+=40;        s.erase(0,2);        }        else while(s[0]=='X'||s[0]=='L'||s[0]=='C')        {        if(s[0]=='X')   num+=10;        else if(s[0]=='L')  num+=50;        else if(s[0]=='C')  num+=80;        s.erase(0,1);        }                if(s[0]=='I'&&s[1]=='V')        {        num+=4;        s.erase(0,2);        }        else while(s[0]=='I'||s[0]=='V'||s[0]=='X')        {        if(s[0]=='I')   num+=1;        else if(s[0]=='V')  num+=5;        else if(s[0]=='X')  num+=8;        s.erase(0,1);        }        return num;    }};


0 0
原创粉丝点击