首页 > 其他 > 详细

Roman to Integer -- leetcode

时间:2014-12-19 14:29:42      阅读:203      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!