您的位置:首页 > 其它

leetCode 13.Roman to Integer (罗马数字转整形) 解题思路和方法

2015-07-05 20:54 363 查看
Roman to Integer

Given a roman numeral, convert it to an integer.

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

思路:开始解此题的时候,立马想到上题的反转公式。话不多说,上代码。具体思路代码注释。

public class Solution {
public int romanToInt(String s) {
//将用到数据数组保存
int[] v1 = new int[]{1000,500,100,50,10,5,1};
String[] k1 = new String[]{"M", "D","C", "L","X","V","I"};
//双字符数组
int[] v2 = new int[]{900,400,90,40,9,4};
String[] k2 = new String[]{"CM","CD","XC", "XL", "IX", "IV"};

String temp = "";
int num = 0;//返回的数字
boolean isBreak = false;//双字符是否已经处理

while(s.length() > 0){
//字符串长度大于2
if(s.length() >= 2){
//取前两位字符
temp = s.substring(0,2);
//与k2字符串比较
for(int i = 0; i < k2.length; i++){
//存在相等
if(k2[i].equals(temp)){
num += v2[i];//将数字加上
s = s.substring(2);//字符串更新
isBreak = true;//爽字符已处理,单字符不再处理
break;
}
}
//如果双字符没有匹配,则截取单字符处理
if(!isBreak){
temp = s.charAt(0) + "";
for(int j = 0; j < k1.length; j++){
if(k1[j].equals(temp)){
num += v1[j];
s = s.substring(1);
break;
}
}
}else{
isBreak = false;
}
}
//处理最后一个字符
else{
temp = s.charAt(0) + "";

for(int j = 0; j < k1.length; j++){
if(k1[j].equals(temp)){
num += v1[j];
s = s.substring(1);
break;
}
}
}
//System.out.println(s);
}
return num;
}
}
上述解法总体上思路比较清楚,但是相比下面的解法,整体代码上冗长,而且效率上也要低一些。

public class Solution {
public int romanToInt(String s) {
char[] ch = s.toCharArray();//转成字符数组
int num = 0;
//字符数组遍历
for(int i = 0; i < ch.length - 1; i++){
//如果字符与之后的对应数值小,则本字符对应数值为减,否则为加
if(getRomanValue(ch[i]) < getRomanValue(ch[i+1])){
num -= getRomanValue(ch[i]);
}
else{
num += getRomanValue(ch[i]);
}
}
//加上最后一个字符
num += getRomanValue(ch[ch.length - 1]);
return num;
}
//第字符保存在方法中,返回相应数值
public static int getRomanValue(char c) {
switch(c) {
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;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: