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

[LeetCode]Roman to Integer

时间:2014-05-14 23:49:52      阅读:515      评论:0      收藏:0      [点我收藏+]

标签:style   blog   class   code   c   tar   

Given a roman numeral, convert it to an integer.

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

class Solution {
public:

    int romanToInt(string s)
    {
    int roman[128];
   	roman[‘I‘] = 1;
	roman[‘V‘] = 5;
	roman[‘X‘] = 10;
	roman[‘L‘] = 50;
	roman[‘C‘] = 100;
	roman[‘D‘] = 500;
	roman[‘M‘] = 1000;
	int ans = 0;
	int pre;
	//大数后面是小数,则减;
	//大数前面是小数,则加;
	for(int i = s.size() - 1; i >= 0; i--)
	{
		if(ans == 0) 
		{
			ans = roman[s[i]];
		}
		else
		{
			if(pre > roman[s[i]]) 
			{
				ans -= roman[s[i]];
			}
			else 
			{
				ans += roman[s[i]];
			}
		}
		pre = roman[s[i]];
	}
	return ans;
    }
};

罗马数字简介,参考:

[LeetCode]Integer to Roman - Jet_yingjia的专栏 - 博客频道 - CSDN.NET 

http://blog.csdn.net/jet_yingjia/article/details/25814977


[LeetCode]Roman to Integer,布布扣,bubuko.com

[LeetCode]Roman to Integer

标签:style   blog   class   code   c   tar   

原文地址:http://blog.csdn.net/jet_yingjia/article/details/25837151

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