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

Roman to Integer -- leetcode

时间:2014-12-19 14:30:53      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:leetcode   roman   罗马数字   转换   面试   

Given a roman numeral, convert it to an integer.

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


class Solution {
public:
    int romanToInt(string s) {
        int weight[26];
        int *map = &weight[-'A'];
        map['I'] =  1; map['V'] =   5; map['X'] = 10;
        map['L'] = 50; map['C'] = 100; map['D'] = 500;
        map['M'] = 1000;

        int result = 0;
        for (int i=0; i<s.size(); i++) {
                if (i != s.size()-1 && map[s[i]] < map[s[i+1]])
                        result -= map[s[i]];
                else
                        result += map[s[i]];
        }

        return result;
    }
};

转换比较简单, 比后面大或等,则累加;比后面小,则累减。

Roman to Integer -- leetcode

标签:leetcode   roman   罗马数字   转换   面试   

原文地址:http://blog.csdn.net/elton_xiao/article/details/42027427

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