LeetCode Roman to Integer && Integer to Roman

Roman to Integer

 :Given a roman numeral, convert it to an integer.Input is guaranteed to be within the range from 1 to 3999. 

题目大意是给你一个罗马数字让你转化为阿拉伯数字。不清楚罗马数

字请看维基百科的罗马数字的定义。这道题我是用map来做的,先将各个字母对应的

数字含义存到map里然后再通过遍历字符串来获得其数值。

代码:

class Solution {
public:
    int romanToInt(string s) {
        map<char, int> transition;
		transition['I'] = 1;
		transition['V'] = 5;
		transition['X'] = 10;
		transition['L'] = 50;
		transition['C'] = 100;
		transition['D'] = 500;
		transition['M'] = 1000;
		map<char, int>::iterator iter;

		int result = 0;
		char last = s[0];
		char current = s[0];

		for(int i = 0; i < s.length(); i++)
		{
			iter = transition.find(s[i]);
			if(iter != transition.end())
			{
				current = s[i];
				int lastValue = transition[last];
				int currentValue = transition[current];
				if(currentValue > lastValue)result = result + currentValue - 2 * lastValue;
				else result += currentValue;
				last = s[i];				
			}
		}
		return result;
    }
};

因为计算罗马数字的数值时需要看当前字母与前一个字母的大小才能决定是加还是减,所以这里定义了一个lastValue和一个currentValue。


Integer to Roman

 : Given an integer, convert it to a roman numeral. Input is guaranteed to be within the range from 1 to 3999.
这题刚好和上题相反,给你一个数让你转化为罗马数字。

这次用了一个转换表,根据这个字符串转换表来控制加入的字母。

代码:

class Solution {
public:
	string transition;
	string returnResult(int times, int n){
		transition = "IVXLCDM"; 
		string result;
		if(times < 4)result.append(times, transition[n]);
		else if(times == 4)result.append(1, transition[n]), result.append(1, transition[n + 1]);
		else if(times == 5)result.append(1, transition[n + 1]);
		else if(times >= 6 && times <= 8){
			result.append(1, transition[n + 1]);
			result.append(times - 5, transition[n]);
		}
		else {
			result.append(1, transition[n]);
			result.append(1, transition[n + 2]);
		}
		return result;
	}
    string intToRoman(int num) {
		transition = "IVXLCDM";        
		string result = "";
		int div = 1000;
		int index = 6;
		while(num != 0 && index >= 0){
			int tmp = num / div;
			if(tmp > 0)result += returnResult(tmp, index);
			num %= div;
			div /= 10;
			index -= 2;
		}	
		return result;
    }

};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值