罗马数字转换为整数

题目原型

Given a roman numeral, convert it to an integer.

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

首先要认识一些罗马符号:I表示1,V表示5,X表示10,L表示50,C表示100,D表示500,M表示1000. 然后,从前往后扫描字符串,设置4个变量:临时变量(temp)、前一个数字变量(pre)、当前数字变量(current)、结果变量(result)。

1.如果当前处理的字符对应的值和上一个字符一样,那么临时变量(temp)加上当前这个字符(current)

2.如果当前比前一个大,说明这一段的值应该是当前(current)这个值减去前面记录下的临时变量(temp)中的值。例如 IV = 5 - 1。

3.如果当前比前一个小,那么就可以先将临时变量(temp)的值加到结果(result)中,临时变量值(temp)变为当前变量(current)值,然后开始下一段记录。比如VI = 5 + 1。

完成任何一步后,pre的值始终为current的值。

最后:result = result + temp

具体代码如下:

	public int getValue(char ch)
	{
		switch(ch)
		{
			case 'I': return 1;   
			case 'V': return 5;  
			case 'X': return 10;  
			case 'L': return 50;  
			case 'C': return 100;  
			case 'D': return 500;  
			case 'M': return 1000;
			default: return 0;
		}
	}
	public int romanToInt(String s)
	{
		int result = 0;
		int temp = 0;//设立临时变量
		int current = 0;//当前变量
		int pre = 0;//前一个值
		char ch ;//储存逐个读取的单个字符
		temp = getValue(s.charAt(0));
		pre = temp;
		for(int i = 1;i<s.length();i++)
		{
			ch = s.charAt(i);
			current = getValue(ch);
			//分三种情况
			if(current==pre)
			{
				//当前值和前一个值相等
				temp+=current;
				pre = current;
			}
			else if(current<pre)
			{
				//当前值比前一个小
				result+=temp;
				temp = current;
				pre = current;
			}
			else
			{
				//当前值比前一个大
				temp = current - temp;
				pre = current;
			}
		}
		result+=temp;
		return result;
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值