罗马转整数
http://www.lintcode.com/zh-cn/problem/roman-to-integer/
给定一个罗马数字,将其转换成整数。
返回的结果要求在1到3999的范围内。
说明
样例
IV
-> 4
XII
-> 12
XXI
-> 21
XCIX
-> 99
public class Solution {
/*
* @param s: Roman representation
* @return: an integer
*/
Map<Character, Integer> map = new HashMap<Character, Integer>();
public Solution(){
initRomanMap();
}
//TC = O(n)
public int romanToInt(String s) {
if(s==null) return 0;
int n = s.length();
int res=0;
for(int i=0; i<n; i++){
int cur = map.get(s.charAt(i));
int follow = 0;
if(i!=n-1)
follow = map.get(s.charAt(i+1));
if(cur<follow){
res+=follow-cur;
i++;
}else{
res+=cur;
}
}
return res;
}
public void initRomanMap(){
//Symbol I V X L C D M
//Value 1 5 10 50 100 500 1,000
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);
}
};
整数转罗马
http://www.lintcode.com/zh-cn/problem/integer-to-roman/#
给定一个整数,将其转换成罗马数字。
返回的结果要求在1-3999的范围内。
说明
样例
4
-> IV
12
-> XII
21
-> XXI
99
-> XCIX
更多案例,请戳 http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm
public class Solution {
/*
* @param s: Roman representation
* @return: an integer
*/
public String intToRoman1(int num) {
StringBuffer res = new StringBuffer("");
int[] values = new int[]{1000,900,500,400,100,90,50,40,10,9,5,4,1};
String[] romans = new String[]{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
int n = values.length;
for(int i=0; i<n; i++){
int k = num/values[i];
while(k>0){
res.append(romans[i]);
k--;
}
num = num%values[i];
}
return res.toString();
}
public String intToRoman(int num) {
String[] M = new String[]{"","M","MM","MMM"};
String[] C = new String[]{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"};
String[] X = new String[]{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"};
String[] I = new String[]{"","I","II","III","IV","V","VI","VII","VIII","IX"};
return M[num/1000]+C[num%1000/100]+X[num%1000%100/10]+I[num%1000%100%10];
}
};