forked from orlandophp/04-Roman-Numerals
-
Notifications
You must be signed in to change notification settings - Fork 1
/
RomanNumeral.php
130 lines (120 loc) · 2.82 KB
/
RomanNumeral.php
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
124
125
126
127
128
129
130
<?php
/**
* RomanNumeral
*
* @package RomanNumeral
* @version 1.0
* @author Ketema Harris
*/
class RomanNumeral
{
/**
* _integerValue
*
* @var integer
*/
private $_integerValue = null;
/**
* _romanValue
*
* @var string
*/
private $_romanValue = null;
/**
* _roman2decimal
*
* @var array
*/
private $_roman2decimal = array (
'M' => 1000,
'CM' => 900,
'D' => 500,
'CD' => 400,
'C' => 100,
'XC' => 90,
'L' => 50,
'XL' => 40,
'X' => 10,
'IX' => 9,
'V' => 5,
'IV' => 4,
'I' => 1,
'N' => 0,
);
/**
* __construct
*
* @return object
*/
public function __construct ( )
{
return $this;
} //END __construct
/**
* parseRoman
*
* @param mixed $romanNumeral
* @return array
*/
public function parseRoman( $romanNumeral )
{
if( empty( $romanNumeral ) )
{
return null;
}
else
{
return str_split( $romanNumeral );
}
} //END parseRoman
/**
* toInt
*
* @param mixed $romanNumeral
* @return integer
*/
public function toInt( $romanNumeral )
{
$calculated = 0;
$last = 'N';
$romanNumerals = array_reverse( $this->parseRoman( $romanNumeral ) );
foreach ($romanNumerals as $romanNumeral)
{
if( $this->_roman2decimal[$romanNumeral] < $this->_roman2decimal[$last] )
{
$calculated -= $this->_roman2decimal[$romanNumeral];
}
else
{
$calculated += $this->_roman2decimal[$romanNumeral];
}
$last = $romanNumeral;
}
$this->_integerValue = $calculated;
$this->_romanValue = $romanNumeral;
return $calculated;
} //END toInt
/**
* fromInt
*
* @param integer $integer
* @return string
*/
public function fromInt( $integer )
{
//Make sure we have an integer
$integer = intval( $integer );
$romanNumeral = '';
if ( $integer == 0 ) return 'N';
foreach( $this->_roman2decimal as $romanIndex => $integerValue )
{
while( $integer >= $integerValue && $integerValue != 0 ){
$integer -= $integerValue;
$romanNumeral .= $romanIndex;
}
}
$this->_romanValue = $romanNumeral;
$this->_integerValue = $integer;
return $romanNumeral;
} //END fromInt
}