罗马数字转换为整数
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
具体代码如下:
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; }
相关文章推荐
- 整数转换成罗马数字
- 计蒜客 难题题库 013 整数转换成罗马数字
- 【计蒜客系列】挑战难题14:罗马数字转换成整数
- Integer to Roman 整数转换成罗马数字
- 罗马数字转换成整数(注意罗马数字的大小表示问题)
- 第14题:罗马数字转换成整数
- 罗马数字转换为整数
- 计蒜客 挑战难题 第14题:罗马数字转换成整数
- 罗马数字转换成整数
- 计蒜课挑战难题:罗马数字转换成整数
- 将罗马数字转换成整数
- 计蒜客 第14题:罗马数字转换成整数
- 整数转换成罗马数字
- 整数转换成罗马数字
- 剑指offer题解 把字符串转换成整数(todo:考虑大整数的情况)
- java: 查表法将十进制整数转换成二进制、八进制、十六进制
- Java整数-字节,字节-字符,字节数组-十六进制字符串转换
- 用递归的方法将一个整数n转换成字符串
- ruby中的整数、浮点数、字符串之间的相互转换
- C语言中的整数自动转换原则