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

Leetcode: Roman to Integer, Integer to Roman

时间:2014-05-09 09:46:36      阅读:298      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   java   tar   

Roman to Integer

Integer to Roman 

这两题纯粹是模拟题,关键就是理解罗马计数,直接上代码吧

bubuko.com,布布扣
class Solution {
public:
    int romanToInt(string s) {
         int result = 0;
         for (int i = 0; i < s.size(); ++i) {
             if (i > 0 && map(s[i]) > map(s[i-1])) {
                 result += (map(s[i]) - 2 * map(s[i-1]));
             } else {
                 result += map(s[i]);
             }
         }
         return result;
    }
    
    inline int map(const char c) {
        switch(c) {
            case I : return 1;
            case V : return 5;
            case X : return 10;
            case L : return 50;
            case C : return 100;
            case D : return 500;
            case M : return 1000;
            default  : return 0;
        }
    }
};
bubuko.com,布布扣

 

bubuko.com,布布扣
class Solution {
public:
    string intToRoman(int num) {
        const int radix[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        const string symbol[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        string roman;
        for (int i = 0; num > 0; ++i) {
            int count = num / radix[i];
            num %= radix[i];
            for (; count > 0; --count) {
                roman += symbol[i];
            }
        }
        return roman;
    }
};
bubuko.com,布布扣

 

 

Leetcode: Roman to Integer, Integer to Roman,布布扣,bubuko.com

Leetcode: Roman to Integer, Integer to Roman

标签:style   blog   class   code   java   tar   

原文地址:http://www.cnblogs.com/wwwjieo0/p/3717598.html

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