请将给出的罗马数字转化为整数
保证输入的数字范围在1 到 3999之间。
public class Solution {
public static void main(String[] args) {
System.out.println(new Solution().romanToInt("DCXXI"));
}
/**
* @param s string字符串
* @return int整型
*/
public int romanToInt(String s) {
// write code here
int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] strs = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
int temp = 0;
StringBuilder s1 = new StringBuilder(s);
for (int i = 0; i < values.length; i++) {
while (s1.indexOf(strs[i]) == 0) {
temp += values[i];
s1.delete(0, strs[i].length());
}
}
return temp;
}
} Leetcode#13. Roman to Integer(罗马数字转整数)
import java.util.HashMap;
/**
* 13\. Roman to Integer(罗马数字转整数)
* 给定一个罗马数字,将其转换成整数。输入确保在 1 到 3999 的范围内。
*/
public class Solution {
public static void main(String[] args) {
Solution13 solution13 = new Solution13();
String s = "IV";
System.out.println(solution13.romanToInt(s));
}
/**
* 相同的数字连写,所表示的数等于这些数字相加得到的数,如 Ⅲ=3;
* 小的数字在大的数字的右边,所表示的数等于这些数字相加得到的数,如 Ⅷ=8、Ⅻ=12;
* 小的数字(限于 Ⅰ、X 和 C)在大的数字的左边,所表示的数等于大数减小数得到的数,如 Ⅳ=4、Ⅸ=9。
* 利用 map 来完成罗马数字的 7 个数字符号:I、V、X、L、C、D、M 和整数的映射关系,然后根据上面的解释来模拟完成即可。
*
* @param s
* [@return](/profile/547241) */
public int romanToInt(String s) {
HashMap map = new HashMap();
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 len = s.length();
int res = map.get(s.charAt(len - 1));
for (int i = len - 2; i >= 0; i--) {
if (map.get(s.charAt(i)) < map.get(s.charAt(i + 1))) {
res -= map.get(s.charAt(i));
} else {
res += map.get(s.charAt(i));
}
}
return res;
}
}
count every Symbol and add its value to the sum, and minus the extra part of special cases.
public int romanToInt(String s) { int sum=0; if(s.indexOf("IV")!=-1){sum-=2;} if(s.indexOf("IX")!=-1){sum-=2;} if(s.indexOf("XL")!=-1){sum-=20;} if(s.indexOf("XC")!=-1){sum-=20;} if(s.indexOf("CD")!=-1){sum-=200;} if(s.indexOf("CM")!=-1){sum-=200;} char c[]=s.toCharArray(); int count=0; for(;count<=s.length()-1;count++){ if(c[count]=='M') sum+=1000; if(c[count]=='D') sum+=500; if(c[count]=='C') sum+=100; if(c[count]=='L') sum+=50; if(c[count]=='X') sum+=10; if(c[count]=='V') sum+=5; if(c[count]=='I') sum+=1; } return sum; }