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

【leetcode】7 Roman to Integer

时间:2015-05-11 10:45:00      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

罗马字符转整数

注意事项:

1 几个罗马字符对应的整数

 ‘I‘:  1;
 ‘V‘:  5;
 ‘X‘:  10;
 ‘L‘:   50;
 ‘C‘:  100;
 ‘D‘:  500;
 ‘M‘: 1000;

2 对于DC这种前者大于后者的好处理,

对于CD这种前者小于后者的,相当于C+D-2*C

class Solution {
public:
    int toInt(char x){
        switch(x){
            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;
        }
       
    }
    int romanToInt(string s) {
         int rest=toInt(s[0]);
         for(int i=1;i<s.length();i++){
             if(toInt(s[i-1])<toInt(s[i])){
                 rest+=toInt(s[i])-2*toInt(s[i-1]);
             }else
                 rest+=toInt(s[i]);
         }
         return rest;
       
    }
};

【leetcode】7 Roman to Integer

标签:

原文地址:http://www.cnblogs.com/wygyxrssxz/p/4493791.html

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