Roman digits

How can i transform a number made from arabian digits into a number made from roman digits?

Example: 56 becomes LVI
You shoul check the number if it is smaller or greater of a roman digit.
eg: 56:

56 -> Greatest smaller roman digit : 'L'
56 - 50 (L) = 6
6 -> Greatest smaller roman digit : 'V'
6 - 5 (V) = 1
1 -> Greatest smaller roman digit : 'I'

I've made something like that some time ago, the function I implemented was something like this:
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
while (i>=100)
{
	i-=100;
	tempr+='C';
}
if (i>=99)
{
	i-=99;
	tempr+="IC";
}
if (i>=90)
{
	i-=90;
	tempr+="XC";
}
if (i>=50)
{
	i-=50;
	tempr+='L';
}
if (i>=49)
{
	i-=49;
	tempr+="IL";
}
if (i>=40)
{
	i-=40;
	tempr+="XL";
}
while (i>=10)
{
	i-=10;
	tempr+='X';
}
if (i>=9)
{
	i-=9;
	tempr+="IX";
}
if (i>=5)
{
	i-=5;
	tempr+='V';
}
if (i>=4)
{
	i-=4;
	tempr+="IV";
}
while (i>0)
{
	i--;
	tempr+='I';
}

where i was the number to be converted and tempr a std::string holding the result.

(You could enlarge this for handling higher vaues)
Last edited on
Woodnt it be easier to use two arrays with maching elements instead of a whole bunch of if-statements? Eg:
1
2
int digits[size]={0,4,5,9,...}
string RomanDigits[size]={"I","IV","V","IX",...}

And then use a for-loop inside a while loop to go through them (in reverse order):
1
2
3
4
5
6
7
8
9
10
11
12
while (input>0)
{
    for (int i=size;i>=0;i--)
    {
        if (input>=digits[i])
        {
            input-=digits[i];
            tempr+=RomanDigits[i];
            break;
        }
    }
}
Roman numerals are base 10, luckily, so it's not too hard to convert between systems.
The roman symbols stop at 1000, so after that, I'll use the symbol, folloed an apostrophe. This multiplies the value of the symbol by 1000. In reality, this is represented by a line on top of the symbol.
For each power of ten, there are two symbol that need to be used, which I will call the base, and the quintuple, which is always five times the base:
1s: b: I, q: V
10s: X, L
100s: C, D
1000s: M, V'
10000s: X', L'
And so on.

To represent a decimal digit, we merely need to use a combination of bases and quintuples:
If the digit is 0, then nothing is used
1: base
2: base, base
3: bbb
4: bq
5: q
6: qb
7: qbb
8: qbbb
9: base, and the base of the next order of magnitude

I'll use 8192 as my example:
First, break up the number into decimal digits: {8,1,9,2}
8: qbbb -> The quintuple of 1000s is V', and it's base is M, so V'MMM
1: b -> The base of 100s is C, so C
9: bb+ -> XC
2: bb -> II
We string together everything in the same order: V'MMMCXCII
Topic archived. No new replies allowed.