首页 > 其他 > 详细

leetcode Roman to Integer

时间:2014-03-27 13:56:37      阅读:468      评论:0      收藏:0      [点我收藏+]

Given a roman numeral, convert it to an integer.

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

罗马数字共有7个,即I(1)、V(5)、X(10)、L(50)、C(100)、D(500)和M(1000)。按照下述的规则可以表示任意正整数。需要注意的是罗马数字中没有“0”,与进位制无关。

  • 重复数次:一个罗马数字重复几次,就表示这个数的几倍。
  • 右加左减:
    • 在较大的罗马数字的右边记上较小的罗马数字,表示大数字加小数字。
    • 在较大的罗马数字的左边记上较小的罗马数字,表示大数字减小数字
bubuko.com,布布扣
#include <iostream>
#include <map>
#include <string>
using namespace std;

int romanToInt(string s){
    int length = s.length();
    if (length < 1) return 0;
    map<int,int> romanMap;
    romanMap[I] = 1;      romanMap[V] = 5;
    romanMap[X] = 10;     romanMap[L] = 50;
    romanMap[C] = 100;    romanMap[D] = 500;
    romanMap[M] = 1000;
    int index = length - 1 , sum = romanMap[s[index]];
    while (--index >= 0) {
        if (romanMap[s[index+1]] >romanMap[s[index]]) sum -= romanMap[s[index]];
        else sum += romanMap[s[index]];
    }
    return sum;
}

int main(){
    cout<<romanToInt("DCXXI")<<endl;
    return 0;
}
bubuko.com,布布扣

leetcode Roman to Integer,布布扣,bubuko.com

leetcode Roman to Integer

原文:http://www.cnblogs.com/xiongqiangcs/p/3627969.html

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