首页 > 其他 > 详细

LeetCode 13 罗马数字转换为int型

时间:2015-12-04 10:51:50      阅读:329      评论:0      收藏:0      [点我收藏+]
 1 class Solution {
 2 public:
 3 /*
 4 string M[] = {"", "M", "MM", "MMM"};    //千位,从1000到3000
 5 string C[] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"};  //百位,从100到900
 6 string X[] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"};  //十位,从10到90
 7 string I[] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};  //个位,从1到9
 8 */
 9    int romanToInt(string s){
10          int result = switchNum(s[0]);
11          for(int i=1; i<s.size(); ++i){
12              if(switchNum(s[i-1]) < switchNum(s[i])){
13                  //比如CD 遍历到C的时候已经加过100了,所以遍历到D的时候需要减两次100
14                  result += switchNum(s[i]) - 2*switchNum(s[i-1]);
15              }else{
16                  result += switchNum(s[i]);
17              }
18          }
19          return result;
20    }
21    int switchNum(char c){
22        switch (c){
23            case I: return 1;
24            case V: return 5;
25            case X: return 10;
26            case L: return 50;
27            case C: return 100;
28            case D: return 500;
29            case M: return 1000;
30            default:
31             return 0;
32        }
33    }
34 };

 

LeetCode 13 罗马数字转换为int型

原文:http://www.cnblogs.com/ackerzju/p/5018449.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!