1. 程式人生 > >Roman to Integer(羅馬數字轉換成整數)

Roman to Integer(羅馬數字轉換成整數)

**Problem:Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.**
*構數規則:基本字元有7個: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、正常使用時,連寫的數字重複不得超過三次。*
*演算法分析:
(1)掃描各個羅馬字元,若為I X V中的任何一個則判定是否存在下一個羅馬字元,若存在則比較這兩個數大小,若當前數(current)小於下一個數(next),則current=next-current;並且指標加一;否則不做任何操作;
(2)結果值加上當前數,指標加一;
(3)返回結果值。*

class Solution {
public:
    int charToInt(char c){
        switch (c){
            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;
            default
: return -1; } } int romanToInt(string s) { int value=0,cut=0,current,next; for(auto it=s.cbegin();it!=s.cend();it++){ current=charToInt(*it); if(current==-1) cout<<"error"<<endl; if(current==1||current==10||current==100) if
((it+1)!=s.cend()){ next=charToInt(*(it+1)); if(next-current>0){ current=next-current; it++; } } value+=current; } return value; } };