fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <map>
  5. #include <unordered_map>
  6. #include <assert.h>
  7. using namespace std;
  8.  
  9. unordered_map<char, unsigned int> r2i_lut = { {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50} };
  10.  
  11. unsigned int r2i(const string& r)
  12. {
  13. if(r.size()==0) return 0;
  14. if(r.size()==1) return r2i_lut[r[0]];
  15.  
  16. unsigned int res=0;
  17. for(unsigned int i=0; i<r.size(); ++i)
  18. {
  19. if((i<r.size()-1) && (r2i_lut[r[i+1]] > r2i_lut[r[i]])) { res += (r2i_lut[r[i+1]] - r2i_lut[r[i]]); i++; }
  20. else { res += r2i_lut[r[i]]; }
  21. }
  22. return res;
  23. }
  24.  
  25. // Function to convert decimal to Roman Numerals
  26. string i2r(unsigned int number)
  27. {
  28. string res;
  29. int num[] = {1,4,5,9,10,40,50,90,100,400,500,900,1000};
  30. string sym[] = {"I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"};
  31. int i=12;
  32. while(number>0)
  33. {
  34. int div = number/num[i];
  35. number = number%num[i];
  36. while(div--) res+=sym[i];
  37. i--;
  38. }
  39. return res;
  40. }
  41.  
  42.  
  43. const vector<string> test_roman =
  44. {
  45. "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X",
  46. "XI", "XII", "XIII", "XIV", "XV", "XVI", "XVII", "XVIII", "XIX", "XX",
  47. "XXI", "XXII", "XXIII", "XXIV", "XXV", "XXVI", "XXVII", "XXVIII", "XXIX", "XXX",
  48. "XXXI", "XXXII", "XXXIII", "XXXIV", "XXXV", "XXXVI", "XXXVII", "XXXVIII", "XXXIX", "XL",
  49. "XLI", "XLII", "XLIII", "XLIV", "XLV", "XLVI", "XLVII", "XLVIII", "XLIX", "L"
  50. };
  51.  
  52. int main() {
  53. // your code goes here
  54. for(unsigned int i=0; i<test_roman.size();++i) {auto e = test_roman[i]; assert(r2i(e)==i+1); cout << r2i(e) << endl; }
  55. for(unsigned int i=0; i<50; ++i) { assert(test_roman[i].compare(i2r(i+1)) == 0 ); cout << i2r(i+1) << " Test " << test_roman[i] << endl;}
  56. return 0;
  57. }
  58.  
  59.  
Success #stdin #stdout 0s 4536KB
stdin
Standard input is empty
stdout
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
39
40
41
42
43
44
45
46
47
48
49
50
I Test I
II Test II
III Test III
IV Test IV
V Test V
VI Test VI
VII Test VII
VIII Test VIII
IX Test IX
X Test X
XI Test XI
XII Test XII
XIII Test XIII
XIV Test XIV
XV Test XV
XVI Test XVI
XVII Test XVII
XVIII Test XVIII
XIX Test XIX
XX Test XX
XXI Test XXI
XXII Test XXII
XXIII Test XXIII
XXIV Test XXIV
XXV Test XXV
XXVI Test XXVI
XXVII Test XXVII
XXVIII Test XXVIII
XXIX Test XXIX
XXX Test XXX
XXXI Test XXXI
XXXII Test XXXII
XXXIII Test XXXIII
XXXIV Test XXXIV
XXXV Test XXXV
XXXVI Test XXXVI
XXXVII Test XXXVII
XXXVIII Test XXXVIII
XXXIX Test XXXIX
XL Test XL
XLI Test XLI
XLII Test XLII
XLIII Test XLIII
XLIV Test XLIV
XLV Test XLV
XLVI Test XLVI
XLVII Test XLVII
XLVIII Test XLVIII
XLIX Test XLIX
L Test L