[LeetCode-Algorithms-13] "Roman to Integer" (2017.9.22-WEEK3)

来源:互联网 发布:怎么查看手机端口号 编辑:程序博客网 时间:2024/05/23 23:34

题目链接:Roman to Integer


  • 题目描述:

Given a roman numeral, convert it to an integer.
Input is guaranteed to be within the range from 1 to 3999.


(1)思路:这个问题比较简单,首先要搞清楚罗马数字的表达方式,然后对应的把四位表示用数组列举出来,然后由数据范围规定,从1到3900循环匹配(把整数拆分成千位、百位、十位和个位进行查找匹配),直到找到一个整数的罗马数字表达与对应字符串相同。

(2)代码:

class Solution {public:    int romanToInt(string s) {        string m[4] = {"", "M", "MM", "MMM"},               c[10] = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},               x[10] = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},               i[10] = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"};        for (int j = 1; j < 4000; j++)             if (s == m[j/1000] + c[(j%1000)/100] + x[(j%100)/10] + i[j%10])                   return i;        return 0;    }};

(3)提交结果:

这里写图片描述

原创粉丝点击