Convert from Arabic to Roman Numerals
Apr 4, 2019 at 6:39am UTC
I am trying to convert Arabic to Roman Numerals (with the intention to later do the opposite using the same code), however, the test cases are not outputting the correct answers.
Input:
iPhone
xRay
c-Span
m_file
DDT
Expected Output:
1
10
100
1000
49
1000
Observed Output:
1
10
100
1000
500
I now understand an array would have been preferable, however, I have spent so long staring at this code I would prefer to just fix it.
Any advice?
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
#include <string>
#include <iostream>
#include <ctype.h>
using namespace std;
std::string numerals = "VXLCDM" ;
int main()
{
char roman_Numeral;
int arabic_Numeral = 0;
while (cin.get(roman_Numeral) || !cin.eof())
{
roman_Numeral = toupper(roman_Numeral);
// cout << "DEBUG: " << roman_Numeral << '\n';
if (roman_Numeral == 'M' )
{
arabic_Numeral = arabic_Numeral + 1000;
continue ;
}
else if (roman_Numeral == 'D' )
{
roman_Numeral = toupper(cin.peek());
if (numerals.find(roman_Numeral, 5) != std::string::npos)
{
arabic_Numeral = arabic_Numeral - 500;
continue ;
}
else
{
arabic_Numeral = arabic_Numeral + 500;
continue ;
}
}
else if (roman_Numeral == 'C' )
{
roman_Numeral = toupper(cin.peek());
if (numerals.find(roman_Numeral, 4) != std::string::npos)
{
arabic_Numeral = arabic_Numeral - 100;
continue ;
}
else
{
arabic_Numeral = arabic_Numeral + 100;
continue ;
}
}
else if (roman_Numeral == 'L' )
{
roman_Numeral = toupper(cin.peek());
if (numerals.find(roman_Numeral, 3) != std::string::npos)
{
arabic_Numeral = arabic_Numeral - 50;
continue ;
}
else
{
arabic_Numeral = arabic_Numeral + 50;
continue ;
}
}
else if (roman_Numeral == 'X' )
{
roman_Numeral = toupper(cin.peek());
if (numerals.find(roman_Numeral, 2) != std::string::npos)
{
arabic_Numeral = arabic_Numeral - 10;
continue ;
}
else
{
arabic_Numeral = arabic_Numeral + 10;
continue ;
}
}
else if (roman_Numeral == 'V' )
{
roman_Numeral = toupper(cin.peek());
if (numerals.find(roman_Numeral, 1) != std::string::npos)
{
arabic_Numeral = arabic_Numeral - 5;
continue ;
}
else
{
arabic_Numeral = arabic_Numeral + 5;
continue ;
}
}
else if (roman_Numeral == 'I' )
{
roman_Numeral = toupper(cin.peek());
if (numerals.find(roman_Numeral) != std::string::npos)
{
//cout << "---\n";
arabic_Numeral = arabic_Numeral - 1;
continue ;
}
else
{
// cout << "---\n";
arabic_Numeral = arabic_Numeral + 1;
continue ;
}
}
if (!arabic_Numeral == 0)
{
cout << arabic_Numeral << endl;
}
arabic_Numeral = 0;
}
}
Apr 4, 2019 at 8:54am UTC
Topic archived. No new replies allowed.