LeetCode No.13 Roman to Integer

来源:互联网 发布:ae中文版 mac 编辑:程序博客网 时间:2024/06/05 17:13

Given a roman numeral, convert it to an integer.

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

====================================================================================
题目链接:https://leetcode.com/problems/roman-to-integer/
题目大意:将一个罗马数字转成整数,其中罗马数字范围是1到3999。
思路: 先从网上找到罗马数字的个十百千位所对应的字符串存到一个二维数组中,因为罗马数字有一个特点就是:每一层都从后往前扫不会产生冲突。所以我们对给定的罗马数字,根据我们已知的二维数组,遵循从后往前扫的原则,就能得到正确的结果。

附:罗马数字表http://baike.baidu.com/link?url=34unAdxVkigmZLxMoqS3rc_-KNDcaiswFfaRpcwgjmk2mYE_IwyA_7o0BVNz3idHU31t1CH8RPpXabCSiOllSmj7mXdbPBIv954pAH0Fb1pdaYZzWe0JatTpr6FsDZoP
附上代码

class Solution {public:    int romanToInt(string s)     {        string c[4][10]={            {"","I","II","III","IV","V","VI","VII","VIII","IX"},            {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"},            {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"},            {"","M","MM","MMM"}        };        int ans = 0 ;        for ( int i = 3 ; i >= 0 ; i -- )        {            int j = i == 3 ? 3 : 9 ;            for ( ; j > 0 ; j -- )            {                if ( s.substr ( 0 , c[i][j].size() ) == c[i][j] )                 {                int num = pow ( 10 , i ) * j ;                ans += num ;                s = s.substr ( c[i][j].size() ) ;                break ;}            }        }        return ans ;    }   };


0 0