码迷,mamicode.com
首页 > 其他好文 > 详细

Roman to Integer

时间:2015-09-10 15:48:41      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:

Given a roman numeral, convert it to an integer.

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

 

 1  inline int c2n(char c) {  
 2       switch(c) {  
 3         case I: return 1;  
 4         case V: return 5;  
 5         case X: return 10;  
 6         case L: return 50;  
 7         case C: return 100;  
 8         case D: return 500;  
 9         case M: return 1000;  
10         default: return 0;  
11       }  
12     }  
13 class Solution {
14 public:
15     int romanToInt(string s) {
16     
17        
18       // Start typing your C/C++ solution below  
19       // DO NOT write int main() function  
20       int result=0; 
21       int len=s.length();
22       result=c2n(s[0]);
23       for(int i =1; i< len; i++)  
24       {  
25         if(c2n(s[i]) > c2n(s[i-1]))  
26         {  
27           result +=(c2n(s[i]) - 2*c2n(s[i-1]));  
28         }  
29         else  
30         {  
31           result += c2n(s[i]);  
32         }  
33       }  
34       return result;  
35     }  
36 };

 

Roman to Integer

标签:

原文地址:http://www.cnblogs.com/hexhxy/p/4797892.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!