Integer to Roman
Given an integer, convert it to a Roman numeral.
The number is guaranteed to being within the range from 1
to 3999
.
Clarification
What is Roman numeral?
- Https://en.wikipedia.org/wiki/Roman_numerals
- https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
- Http://baike.baidu.com/view/42061.htm
Example
4
-IV
12
-XII
21
-XXI
99
-XCIX
More examples at:http://literacy.kent.edu/minigrants/cinci/romanchart.htm
Analysis:
In Roman numerals, in addition to 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1, other numbers can be "spliced" from the above figures. The Roman characters of the above numbers are:
"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I".
So, for 15, we find 10 and 5, put together is xv,16 is 10+5+1, XVI (here must be from large to small, can take the largest must take the largest, can not be 10 + 4 + 1 + 1).
1 Public classSolution {2 /**3 * @param n4 * The integer5 * @return Roman representation6 */7 8 PublicString Inttoroman (intNumber ) {9 int[] values = { +, the, -, -, -, -, -, +,Ten,9,5,4,1 };TenString[] numerals = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I" }; OneStringBuilder result =NewStringBuilder (); A for(inti =0; i < values.length; i++) { - while(Number >=Values[i]) { -Number-=Values[i]; the result.append (Numerals[i]); - } - } - returnresult.tostring (); + } -}
Roman to Integer
Given a Roman numeral, convert it to an integer.
The answer is guaranteed to being within the range from 1 to 3999.
Clarification
What is Roman numeral?
- Https://en.wikipedia.org/wiki/Roman_numerals
- https://zh.wikipedia.org/wiki/%E7%BD%97%E9%A9%AC%E6%95%B0%E5%AD%97
- Http://baike.baidu.com/view/42061.htm
Example
IV
-4
XII
-12
XXI
-21
XCIX
-99
1 Public classSolution {2 /**3 * @param s Roman representation4 * @return an integer5 */6 Public intRomantoint (String s) {7 if(S.length () <1)return 0;8 intValue =0;9 intPValue = Getromanvalue (S.charat (0));//The value of previous characterTen One for(inti =1; I < s.length (); i++) { A intCvalue =Getromanvalue (S.charat (i)); - if(PValue >=cvalue) { -Value + =PValue; the}Else { -Value-=PValue; - } -PValue =Cvalue; + } -Value + = PValue;//We always add the last value to value. No exception. + returnvalue; A at } - Public intGetromanvalue (Charc) { - Switch(c) { - Case 'I':return 1; - Case 'V':return 5; - Case 'X':return Ten; in Case 'L':return -; - Case 'C':return -; to Case 'D':return -; + Case 'M':return +; - default:return 0; the } * } $}
Integer to Roman & Roman to Integer