How about this:
$romans = 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,
);
$roman = 'MMMCMXCIX';
$result = 0;
foreach ($romans as
value) {
while (strpos($roman, $key) === 0) {
$result += $value;
$roman = substr($roman, strlen($key));
}
}
echo $result;
which should output 3999 for the supplied $roman. It seems to work for my limited testing:
MCMXC = 1990
MM = 2000
MMXI = 2011
MCMLXXV = 1975
You might want to do some validation first as well :-)
Answer from andyb on Stack OverflowRoman To Integer Difficulty
How to convert a Roman numeral to integer in PHP? - Stack Overflow
[PROJECT] Roman Numeral -> Integer Converter
here is my_code in Python 2. detects incorrect inputs; please suggest any better approach!! Thanks
More on reddit.comProblem 13: Roman to Integer
WOW. I just found out the issue, and it was that I was initializing sum,valOne,valTwo all at once, which caused random numbers to be stored in sum, thus it would sometimes have the wrong answer, although valOne and valTwo were always correct.
More on reddit.comI have only started creating an acc in leetcode and the title is the first problem that was given to me, and it was marked as "Easy", and I'd say I'm really frustrated by the fact that I can't even think of the right algorithm to create quickly, considering this was supposed to be easy. I know I'm not that good in programming right now, and I have a lot to learn, but why is this problem supposed to be easy when it is much more complicated than what I think it is? Especially the error handling, I have thought of an algorithm to convert the passed argument to integer, if and only if the input is correct, but I'm having a really bad time thinking of an efficient way to check whether the input is valid roman numeral or not. Is it really that "easy" compared to the medium problems that I have yet to solve?
How about this:
$romans = 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,
);
$roman = 'MMMCMXCIX';
$result = 0;
foreach ($romans as
value) {
while (strpos($roman, $key) === 0) {
$result += $value;
$roman = substr($roman, strlen($key));
}
}
echo $result;
which should output 3999 for the supplied $roman. It seems to work for my limited testing:
MCMXC = 1990
MM = 2000
MMXI = 2011
MCMLXXV = 1975
You might want to do some validation first as well :-)
I am not sure whether you've got ZF or not, but in case you (or any of you who's reading this) do here is my snippet:
$number = new Zend_Measure_Number('MCMLXXV', Zend_Measure_Number::ROMAN);
$number->convertTo (Zend_Measure_Number::DECIMAL);
echo $number->getValue();
- Zend_Measure_Number on framework.zend.com