只写了一个java版本的,思想知道了,语言知识工具,学学语法就行了,所以我就没有写C#与javascript
我自己写的,写的比较粗糙
class Solution {
public int romanToInt(String s) {
Map<Character,Integer> map = new HashMap<Character,Integer>();
map.put('I',1);
map.put('V',5);
map.put('X',10);
map.put('L',50);
map.put('C',100);
map.put('D',500);
map.put('M',1000);
int result = 0;
if(s.length() % 2 != 0){
result += map.get(s.charAt(s.length() - 1));
}
for (int i = 0; i < s.length(); i=i+2) {
if(i + 2 > s.length()) return result;
if(map.get(s.charAt(i)) >= map.get(s.charAt(i + 1))){
result += map.get(s.charAt(i)) + map.get(s.charAt(i + 1));
}else{
result += map.get(s.charAt(i + 1)) - map.get(s.charAt(i));
}
}
return result;
}
}
总结:提交代码时,我的方法提交不了,最终结果跟答案不符,s = "MCMXCVI"时,我走IDE最终结果是正确的,但是在LeetCode提交显示结果是1996,不知道为什么,我都走debug了,也没看出什么,无耐。
贴一张我自己写的代码,在LeetCode运行结果
-------------------------------------分割线------------------------------------------------------
是时候展示真正的技术了EZ~~~~~~~~~~~·
这是网上查的,从后面向前进行计算,先把最后一个值加上,然后赋值给一个中间变量tag,指针向前移动一位,tag指向i-1,这样进行比较,默认tag等于0,第一次比较tag就等于最后一位的值。主要就是tag,就靠tag支撑着逻辑。
我做这道题是一次i加两位,根据s.length()的奇偶数是否单独加上最后一为,下面的方法是直接使用tag,一位位比较然后进行相加,就不用考虑奇偶数了,用不用单独加最后一位了,把最后一位给tag,默认把最后一位添加到结果中去,然后tag跟倒数第二位比较,进行加减,然后tag=倒数第二位数,以此类推。
Map<Character,Integer> map = new HashMap<Character,Integer>();
map.put('I',1);
map.put('V',5);
map.put('X',10);
map.put('L',50);
map.put('C',100);
map.put('D',500);
map.put('M',1000);
int tag = 0;
int res = 0;
for (int i = s.length() - 1; i >= 0; i--){
if(map.get(s.charAt(i)) >= tag){
res += map.get(s.charAt(i));
}else{
res -= map.get(s.charAt(i));
}
tag = map.get(s.charAt(i));
}
return res;
}