13. Roman to Integer

来源:互联网 发布:公共场所网络上报 编辑:程序博客网 时间:2024/05/17 01:58

Problems:

Given a roman numeral, convert it to an integer.

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


Example:

Ⅶ,7

XCIII 93


题目大意是把罗马数字转换成阿拉伯数字。(吐槽一下题目应该给一些罗马数字的表示和表示方法,不过没关系,百度一下就出来了)。

基本字符

I

V

X

L

C

D

M

相应的阿拉伯数字表示为

1

5

10

50

100

500

1000

组数规则:

1、基本数字Ⅰ、X 、C 中的任何一个,自身连用构成数目,或者放在大数的右边连用构成数目,都不能超过三个;放在大数的左边只能用一个。

2、不能把基本数字V 、L 、D 中的任何一个作为小数放在大数的左边采用相减的方法构成数目;放在大数的右边采用相加的方式构成数目,只能使用一个。

3、V 和X 左边的小数字只能用Ⅰ。

4、L 和C 左边的小数字只能用X。

5、D 和M 左边的小数字只能用C。


Code:

class Solution {public:    int romanToInt(string s) {        int num = findInt(s[s.length() - 1]);        int temp1, temp2;        for (int i = s.length() - 2; i >= 0; i--) {            temp1 = findInt(s[i]);            temp2 = findInt(s[i + 1]);            if (temp1 >= temp2) {                num = num + temp1;            } else {                num = num - temp1;            }        }        return num;    }    int findInt(char c) {        if (c == 'I') {            return 1;        }        if (c == 'V') {            return 5;        }        if (c == 'X') {            return 10;        }        if (c == 'L') {            return 50;        }        if (c == 'C') {            return 100;        }        if (c == 'D') {            return 500;        }        if (c == 'M') {            return 1000;        }    }};

做完AC了才发现,写得太复杂了,有点久没写C++,把STL的东西都忘记了,这道题可以用map来实行配对,就可以省去了很多if。


原创粉丝点击