首页 > 学院 > 开发设计 > 正文

【LeetCode 13】 Roman to Integer

2019-11-08 00:48:56
字体:
来源:转载
供稿:网友
/****************************LeetCode 13 Roman to Integer Given a roman numeral, convert it to an integer. Input is guaranteed to be within the range from 1 to 3999.**********************/ int romanToInt(string s) {	if (s.size()<1)	{		return 0;	}	//使用hashmap更合适	int weight[26];	memset(weight, 0, sizeof(weight));	weight['I' - 'A'] = 1;	weight['V' - 'A'] = 5;	weight['X' - 'A'] = 10;	weight['L' - 'A'] = 50;	weight['C' - 'A'] = 100;	weight['D' - 'A'] = 500;	weight['M' - 'A'] = 1000;	int size = s.size();	int pivot = weight[s.at(size - 1) - 'A'];	int result = pivot;	for (int ii = size - 2; ii >= 0; ii--)	{		int cur = weight[s[ii] - 'A'];		if (cur >= pivot) //  加上该位上值		{			result += cur;			pivot = cur;		}		else      //减去该位上的值		{			result -= cur;			pivot = cur;		}	}	return result;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表