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

Roman to Integer

时间:2015-04-12 16:12:26      阅读:100      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!