您的位置:首页 > 其它

罗马数字转换为整数

2013-12-30 11:18 225 查看
题目原型

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: