首页 > 其他 > 详细

[LeetCode]13.Roman to Integer

时间:2015-01-22 15:25:12      阅读:183      评论:0      收藏:0      [点我收藏+]

【题目】

Given a roman numeral, convert it to an integer.

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

【分析】

这是一种首先会想到的思路:一个一个字母解析,先解析是不是双字母罗马数字,如果不是就按单字母罗马数字解析。

【代码】

/*********************************
*   日期:2015-01-22
*   作者:SJF0115
*   题目: 13.Roman to Integer
*   网址:https://oj.leetcode.com/problems/roman-to-integer/
*   结果:AC
*   来源:LeetCode
*   博客:
**********************************/
#include <iostream>
using namespace std;

class Solution {
public:
    int romanToInt(string s) {
        int result = 0;
        int len = s.length();
        if(len <= 0){
            return result;
        }//if
        for(int i = 0;i < len;++i){
            if(s[i] == 'M'){
                result += 1000;
            }//if
            else if(s[i] == 'D'){
                result += 500;
            }
            else if(s[i] == 'C'){
                if(s[i+1] == 'M'){
                    result += 900;
                    ++i;
                }//if
                else if(s[i+1] == 'D'){
                    result += 400;
                    ++i;
                }
                else{
                    result += 100;
                }
            }
            else if(s[i] == 'L'){
                result += 50;
            }
            else if(s[i] == 'X'){
                if(s[i+1] == 'C'){
                    result += 90;
                    ++i;
                }//if
                else if(s[i+1] == 'L'){
                    result += 40;
                    ++i;
                }
                else{
                    result += 10;
                }
            }
            else if(s[i] == 'V'){
                result += 5;
            }
            else if(s[i] == 'I'){
                if(s[i+1] == 'X'){
                    result += 9;
                    ++i;
                }
                else if(s[i+1] == 'V'){
                    result += 4;
                    ++i;
                }
                else{
                    result += 1;
                }
            }
        }//for
        return result;
    }
};

int main(){
    Solution solution;
    string roman = "XCVIII";
    int result = solution.romanToInt(roman);
    // 输出
    cout<<result<<endl;
    return 0;
}

技术分享

[LeetCode]13.Roman to Integer

原文:http://blog.csdn.net/sunnyyoona/article/details/43020099

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