forked from jpcsousa/codejam
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRomanNum.cpp
More file actions
executable file
·38 lines (35 loc) · 1.31 KB
/
RomanNum.cpp
File metadata and controls
executable file
·38 lines (35 loc) · 1.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include<iostream>
#include<string>
using namespace std;
string fill( char c, int n )
{
string s;
while( n-- ) s += c;
return s;
}
/* Converts an integer in the range [1, 4000) to a lower case Roman numeral*/
string toRoman( int n )
{
if( n < 4 ) return fill( 'i', n );
if( n < 6 ) return fill( 'i', 5 - n ) + "v";
if( n < 9 ) return string( "v" ) + fill( 'i', n - 5 );
if( n < 11 ) return fill( 'i', 10 - n ) + "x";
if( n < 40 ) return fill( 'x', n / 10 ) + toRoman( n % 10 );
if( n < 60 ) return fill( 'x', 5 - n / 10 ) + 'l' + toRoman( n % 10 );
if( n < 90 ) return string( "l" ) + fill( 'x', n / 10 - 5 ) + toRoman( n % 10 );
if( n < 110 ) return fill( 'x', 10 - n / 10 ) + "c" + toRoman( n % 10 );
if( n < 400 ) return fill( 'c', n / 100 ) + toRoman( n % 100 );
if( n < 600 ) return fill( 'c', 5 - n / 100 ) + 'd' + toRoman( n % 100 );
if( n < 900 ) return string( "d" ) + fill( 'c', n / 100 - 5 ) + toRoman( n % 100 );
if( n < 1100 ) return fill( 'c', 10 - n / 100 ) + "m" + toRoman( n % 100 );
if( n < 4000 ) return fill( 'm', n / 1000 ) + toRoman( n % 1000 );
return "?";
}
int main() {
cout << toRoman(3) << endl;
cout << toRoman(300) << endl;
cout << toRoman(3999) << endl;
cout << toRoman(1) << endl;
cout << toRoman(50) << endl;
return 0;
}