Integer to Roman & Roman to Integer
Integer to Roman
Given an integer, convert it to a roman numeral.
The number is guaranteed to be within the range from 1
to 3999
.
Clarification
Example
4
-> IV
12
-> XII
21
-> XXI
99
-> XCIX
more examples at: http://literacy.kent.edu/Minigrants/Cinci/romanchart.htm
分析:
在罗马数字里,除了1000, 900, 500, 400, 100,90, 50, 40, 10, 9, 5, 4, 1 ,其它数字都可以由以上数字“拼接”而成。以上数字的罗马字符为:
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" 。
所以,对于15,我们找出10和5,放在一起就是XV,16就是10+5+1, XVI(这里一定是从大到小,能够取最大就必须取最大,不能是 10 + 4 + 1 + 1).
1 public class Solution { 2 /** 3 * @param n 4 * The integer 5 * @return Roman representation 6 */ 7 8 public String intToRoman(int number) { 9 int[] values = { 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 }; 10 String[] numerals = { "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I" }; 11 StringBuilder result = new StringBuilder(); 12 for (int i = 0; i < values.length; i++) { 13 while (number >= values[i]) { 14 number -= values[i]; 15 result.append(numerals[i]); 16 } 17 } 18 return result.toString(); 19 } 20 }
Roman to Integer
Given a roman numeral, convert it to an integer.
The answer is guaranteed to be within the range from 1 to 3999.
Clarification
Example
IV
-> 4
XII
-> 12
XXI
-> 21
XCIX
-> 99
1 public class Solution { 2 /** 3 * @param s Roman representation 4 * @return an integer 5 */ 6 public int romanToInt(String s) { 7 if(s.length() < 1) return 0; 8 int value = 0; 9 int pValue = getRomanValue(s.charAt(0)); // the value of previous character 10 11 for (int i = 1; i < s.length(); i++) { 12 int cValue = getRomanValue(s.charAt(i)); 13 if (pValue >= cValue) { 14 value += pValue; 15 } else { 16 value -= pValue; 17 } 18 pValue = cValue; 19 } 20 value += pValue; // we always add the last value to value. No exception. 21 return value; 22 23 } 24 public int getRomanValue(char c) { 25 switch(c) { 26 case 'I': return 1; 27 case 'V': return 5; 28 case 'X': return 10; 29 case 'L': return 50; 30 case 'C': return 100; 31 case 'D': return 500; 32 case 'M': return 1000; 33 default: return 0; 34 } 35 } 36 }