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

Leetcode Roman to Integer

时间:2014-12-21 16:42:41      阅读:193      评论:0      收藏:0      [点我收藏+]

标签:

用了一下template来打表


    template<class T>
    int indexOf(T array[7], T x){
        for(int i = 0; i < 7; i++){
            if(x == array[i])
                return i;
        }
        return -1;
    }
    int romanToInt(string s) {
        string twos [7] = {"CM","CD","XC", "XL", "IX", "IV", "OO"};
        char ones [7] = {'M', 'D', 'C', 'L', 'X', 'V','I'};
        int val2[7] = {900, 400, 90, 40, 9, 4, -1};
        int val1[7] = {1000, 500, 100, 50, 10, 5, 1};
        
        int ans = 0, n = s.size();
        string tmp;
        for(int i = 0; i < n;){
            if(i < n-1 && indexOf(twos, s.substr(i, 2)) != -1){
                ans += val2[indexOf(twos, s.substr(i, 2))];
                i = i+2;
            }
            else{
                ans += val1[ones, indexOf(ones, s[i])];
                i++;
            }
        }
        return ans;
    }


Leetcode Roman to Integer

标签:

原文地址:http://blog.csdn.net/hjlovecl/article/details/42060857

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