Given an integer, convert it to a Roman numeral.
The number is guaranteed to being within the range from 1
to 3999
.
Has you met this question in a real interview?
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
For the original question on Leetcode, see my previous blog, Integer to Roman.
Solution One:
classSolution { Public: /** * @param n the integer * @return Roman representation*/ stringInttoroman (intN) {stringres =""; Vector<vector<string>> v {{"I","II","III","IV","V","VI","VII","VIII","IX"}, {"X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}, {"C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}, {"M","MM","MMM"}}; intCNT = +; for(inti =3; I >=0; --i) {intt = N/CNT; if(t) Res + = v[i][t-1]; N%=CNT; CNT/=Ten; } returnRes; }};
Solution Two:
classSolution { Public: /** * @param n the integer * @return Roman representation*/ stringInttoroman (intN) {stringres =""; Vector<int> val { +, the, -, -, -, -, -, +,Ten,9,5,4,1}; Vector<string> str{"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; for(inti =0; I < val.size (); ++i) { while(N >=Val[i]) {N-=Val[i]; Res+=Str[i]; } } returnRes; }};
Solution Three:
classSolution { Public: /** * @param n the integer * @return Roman representation*/ stringInttoroman (intN) {stringres =""; Vector<string> v1 {"","I","II","III","IV","V","VI","VII","VIII","IX"}; Vector<string> V2 {"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}; Vector<string> V3 {"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}; Vector<string> v4 {"","M","MM","MMM"}; returnV4[n/ +] + v3[(n% +) / -] + v2[(n% -) /Ten] + v1[n%Ten]; }};
[Lintcode] Integer to Roman integers converted to roman numerals