Roman to Integer

Given a roman numeral, convert it to an integer.

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

C++:
01 int romanToInt(string s)
02 {
03     int n=s.size();
04     if(n==0)
05         return 0;
06     int result=0;
07     map<char,int> m;
08     m['M']=1000;
09     m['D']=500;
10     m['C']=100;
11     m['L']=50;
12     m['X']=10;
13     m['V']=5;
14     m['I']=1;
15     for(int i=0;i<n;i++){
16         int t=m[s[i]];
17         if((i<n1)&&(m[s[i+1]]>t))
18              result-=t;
19         else
20              result+=t;
21     }
22     return result;
23 }
Advertisements
This entry was posted in Array and linked list, Number trick. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s