完成度
一点也不会写
自己的代码
错误
照着答案写代码还是错了很多
1、s.length(),有括号
2、new HashMap< , >(),有括号
3、字符用单引号,‘I’
题解
逆序遍历给定的字符串的每一个字符,根据题中的字符表将字符映射为数字,如果小的数在大的数前面就需要拿大的数减去小的数,否则相加。
如:IV,I = 1, V = 5,1 < 5,于是IV = 5 - 1 = 4;
II, 第一个I是1,第二个I还是1,两个数相等,于是II = 1 + 1 = 2;
VI,V = 5, I = 1, 5 > 1,于是VI = 5 + 1 = 6。
class Solution {
public int romanToInt(String s) {
if (s == null || s.length() == 0) {
return 0;
}
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 = map.get(s.charAt(s.length() - 1));
for (int i = s.length() - 2; i >= 0; i--) {
if (map.get(s.charAt(i)) >= map.get(s.charAt(i + 1))) {
result += map.get(s.charAt(i));
}
else {
result -= map.get(s.charAt(i));
}
}
return result;
}
}
原文链接:https://blog.csdn.net/SoulOH/article/details/81605801
补充知识
明天补上map和String