首页 > 其他 > 详细

Roman to Integer

时间:2014-03-11 16:00:42      阅读:490      评论:0      收藏:0      [点我收藏+]

Given a roman numeral, convert it to an integer.

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

首先,学习一下罗马数字
罗马数字是最古老的数字表示方式,比阿拉伯数组早2000多年,起源于罗马
罗马数字有如下符号:
基本字符 I V X L C D M
对应阿拉伯数字 1 5 10 50 100 500 1000
 
 
 
计数规则:
  1. 相同的数字连写,所表示的数等于这些数字相加得到的数,例如:III = 3
  2. 小的数字在大的数字右边,所表示的数等于这些数字相加得到的数,例如:VIII = 8
  3. 小的数字,限于(I、X和C)在大的数字左边,所表示的数等于大数减去小数所得的数,例如:IV = 4
  4. 正常使用时,连续的数字重复不得超过三次
  5. 在一个数的上面画横线,表示这个数扩大1000倍(本题只考虑3999以内的数,所以用不到这条规则)
其次,罗马数字转阿拉伯数字规则(仅限于3999以内):
从前向后遍历罗马数字,如果某个数比前一个数小,则加上该数。反之,减去前一个数的两倍然后加上该数.

同时,这里也用到了STL中map<char,int>,如果小伙伴们知道怎么用,这道题就不怎么难了,当时我也不知道该如何下手,看了别人的思路,豁然开朗。

bubuko.com,布布扣
class Solution {
public:
    int romanToInt(string s) {
        int nLength=s.length();
        if(nLength<1)
            return 0;
        map<char,int> m_stoi;
        m_stoi[I]=1;
        m_stoi[V]=5;
        m_stoi[X]=10;
        m_stoi[L]=50;
        m_stoi[C]=100;
        m_stoi[D]=500;
        m_stoi[M]=1000;
        int i=nLength-1;
        int sum=m_stoi[s[i]];
     i--;
while(i>=0) { if(m_stoi[s[i+1]]>m_stoi[s[i]]) sum-=m_stoi[s[i]]; else sum+=m_stoi[s[i]]; i--; } return sum; } };
bubuko.com,布布扣

 

 

Roman to Integer,布布扣,bubuko.com

Roman to Integer

原文:http://www.cnblogs.com/awy-blog/p/3592744.html

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