[leetcode] 13.Roman to Integer

来源:互联网 发布:淘宝黑搜是什么意思 编辑:程序博客网 时间:2024/05/16 07:07

题目:
Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.
题意:
给定一个罗马数字,转换为整数。
思路:
首先,我们明确,罗马数字各个字符代表什么:
I:1
V:5
X:10
L:50
C:100
D:500
M:1000。
并且比如 IV = 4,IX = 9; XL =40, XC =90, CD = 400, CM = 900。并且只有这6个数字是特殊的,是让后面的数字减去前面的数字。
所以我们不妨扫描的时候将这个罗马数字代表的数字加入结果中。比如扫描IX,先将I代表的1加入,再将X代表的10加入,当到达X的时候,我们判断它前面是不是I,如果是的话说明应该需要用10减去1,因为我们刚才是将1+10了,这个1先要减去一次得到10,还需要再减去一次得到9,也就是扫描到X时发现前面一个字符是I的时候,需要减去两次I代表的值。因为本来就多加了一次,而实际本来需要减去一次,所以当前就要减去两次。
以上。
代码如下:

class Solution {public:    int romanToInt(string s){        int index = 1;        int count = 0;        s = "0" + s;        int size = s.length();        while (index < size) {            switch (s[index]) {                case 'I': count++; break;                case 'V': {                    count = (s[index - 1] == 'I')?count -= 2:count;                    count += 5; break;                }                case 'X': {                    count = (s[index - 1] == 'I')?count -= 2:count;                    count += 10; break;                }                case 'L': {                    count = (s[index - 1] == 'X')?count -= 20:count;                    count += 50; break;                }                case 'C': {                    count = (s[index - 1] == 'X')?count -= 20:count;                    count += 100; break;                }                case 'D': {                    count = (s[index - 1] == 'C')?count -= 200:count;                    count += 500; break;                }                case 'M': {                    count = (s[index - 1] == 'C')?count -= 200:count;                    count += 1000; break;                }            }            index++;        }        return count;    }};
0 0
原创粉丝点击