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

Leetcode13 Roman to Integer

时间:2016-08-08 22:48:41      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

题意:

Given a roman numeral, convert it to an integer.

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

 

分析:

开始准备采用将罗马数字的字符串先划分千位,百位等,但是实际操作起来代码太复杂,而且自己想的逻辑也有问题。

最后采用的方式是从前到后遍历一遍字符即可,加判断来查看字符是不是与前面字符一起组成“小数在大数左边的数字”;

然后依次加数到结果进去即可。

代码:

 1 class Solution {
 2 public:
 3     int romanToInt(string s) {
 4         int result = 0;
 5         for (int i = 0; i < s.size(); ++i) {
 6             if (s[i] == M) {
 7                 if (i - 1 >= 0 && s[i-1] == C) {
 8                     result += 800;
 9                 }
10                 else {
11                     result += 1000;
12                 }
13             }
14             if (s[i] == D) {
15                 if (i - 1 >= 0 && s[i-1] == C) {
16                     result += 300;
17                 }
18                 else {
19                     result += 500;
20                 }
21             }
22             if (s[i] == C) {
23                 if (i - 1 >= 0 && s[i-1] == X) {
24                     result += 80;
25                 }
26                 else {
27                     result += 100;
28                 }
29             }
30             if (s[i] == L) {
31                 if (i - 1 >= 0 && s[i-1] == X) {
32                     result += 30;
33                 }
34                 else {
35                     result += 50;
36                 }
37             }
38             if (s[i] == X) {
39                 if (i - 1 >= 0 && s[i-1] == I) {
40                     result += 8;
41                 }
42                 else {
43                     result += 10;
44                 }
45             }
46             if (s[i] == V) {
47                 if (i - 1 >= 0 && s[i-1] == I) {
48                     result += 3;
49                 }
50                 else {
51                     result += 5;
52                 }
53             }
54             if (s[i] == I){
55                 result += 1;
56             }
57         }
58         return result;
59     }
60 };

 

Leetcode13 Roman to Integer

标签:

原文地址:http://www.cnblogs.com/wangxiaobao/p/5751166.html

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