首页 > 其他 > 详细

Roman to Integer

时间:2015-04-12 16:11:25      阅读:188      评论:0      收藏:0      [点我收藏+]

Given a roman numeral, convert it to an integer.

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

 

AC最快的一次。。每种字母代表一个数字。小的在左边表示右减左,小的在右边表示右加左。如IV表示4, VI表示6.

I, i: 1

V, v: 5

X, x: 10

L, l: 50

C, c: 100

D, d: 500

M, m: 1000

 1 class Solution {
 2 public:
 3     int romanToInt(string s) {
 4         int times = 1;
 5         int result = 0;
 6         for(int i = 0; i < s.length() - 1; i++){
 7             if(toint(s[i]) == toint(s[i+1])) times++;
 8             else if(toint(s[i+1]) > toint(s[i])){
 9                 result -= toint(s[i]) * times;
10                 times = 1;
11             }
12             else{
13                 result += toint(s[i]) * times;
14                 times = 1;
15             }
16         }
17         result += toint(s[s.length()-1]) * times;
18         return result;
19     }
20     int toint(char ch){
21         switch(ch){
22             case I: case i: return 1;
23             case V: case v: return 5;
24             case X: case x: return 10;
25             case L: case l: return 50;
26             case C: case c: return 100;
27             case D: case d: return 500;
28             case M: case m: return 1000;
29         }
30     }
31 };

 

Roman to Integer

原文:http://www.cnblogs.com/amazingzoe/p/4419543.html

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