您的位置:首页 > 其它

leetcode 罗马数字与整数的转换算法

2018-03-31 14:34 549 查看
介绍:

该算法是将罗马数字转换为整数,思路如下:比如IXX,使用临时变量temp保存上一个已经遍历的罗马数字,比如:遍历时是从后往前遍历的:1>  刚开始时,temp = 0; 遍历当前遍历到第一个X,则temp == 0 < 10 == X ,则res = 10;temp = 10;2> 继续向前遍历,又遇到X,此时temp == 10 = 10 == X,则 res = res + 10;即res = 20; temp = 10;3> 继续向前遍历,遇到I,此时temp == 10 > 1 == I; 则 res = res - 1; 即res = 19; temp = 1;循环终止;

代码:

public class Solution {
// 基本思想是根据罗马数字的特征,即左加右减的规律, 比如IX = 9, XI =11
public int romanToInt(String s){
if(s==null||s.length()<1)
return -1;
char ch[]=s.toCharArray();
HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
hm.put('I', 1);
hm.put('V', 5);
hm.put('X', 10);
hm.put('L', 50);
hm.put('C', 100);
hm.put('D', 500);
hm.put('M', 1000);
int res=0;
int temp=0;  临时变量,保存的是当前遍历的上一个数值的值
int value=0;  当前罗马值的大小

for(int i=ch.length-1;i>=0;i--){
value=hm.get(ch[i]);

if(temp<=value){  左加
res+=value;  temp=vlaue;
}else{             右减
res-=value;  temp=value;
}
}
return res;
}


代码:

int romanToInt(string s) {
int tagVal[256];
tagVal['I'] = 1;
tagVal['V'] = 5;
tagVal['X'] = 10;
tagVal['C'] = 100;
tagVal['M'] = 1000;
tagVal['L'] = 50;
tagVal['D'] = 500;
int val = 0;
for(int i = 0; i < s.length(); i++){
if(i+1 >= s.length() || tagVal[s[i+1]] <=          tagVal[s[i]])
val += tagVal[s[i]];
else
val -= tagVal[s[i]];
}
return val;
}


整数转罗马数字

string intToRoman(int num) {
if(num <= 0) return "";
string ret = "";
static int number[13] = {1000, 900, 500, 400, 100,90, 50, 40, 10, 9, 5, 4, 1};
static string flags[13] = {"M","CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

for(int i = 0; i < 13 && num > 0; i++){
if(num < number[i]) continue;
// cout<< i << " " << number[i] << " - " <<flags[i] << endl;
while(num >= number[i]){
num-= number[i];
ret += flags[i];
}

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