Accepted solution to problem number 13 - conversion of Roman numerals to integers
This commit is contained in:
64
13-roman-to-integer.cpp
Normal file
64
13-roman-to-integer.cpp
Normal file
@@ -0,0 +1,64 @@
|
||||
#include <string>
|
||||
#include <map>
|
||||
|
||||
typedef std::map<std::string, unsigned long> RomanNumeral;
|
||||
|
||||
class RomanToIntegerSolution {
|
||||
|
||||
private:
|
||||
RomanNumeral numTable;
|
||||
|
||||
public:
|
||||
int romanToInt(std::string s) {
|
||||
|
||||
unsigned long roman(0);
|
||||
std::string remainder;
|
||||
remainder.resize(s.length());
|
||||
|
||||
unsigned long singleRomanNumerals[255];
|
||||
|
||||
singleRomanNumerals['I'] = 1;
|
||||
singleRomanNumerals['V'] = 5;
|
||||
singleRomanNumerals['X'] = 10;
|
||||
singleRomanNumerals['L'] = 50;
|
||||
singleRomanNumerals['C'] = 100;
|
||||
singleRomanNumerals['D'] = 500;
|
||||
singleRomanNumerals['M'] = 1000;
|
||||
|
||||
numTable["IV"] = 4;
|
||||
numTable["IX"] = 9;
|
||||
numTable["XL"] = 40;
|
||||
numTable["XC"] = 90;
|
||||
numTable["CD"] = 400;
|
||||
numTable["CM"] = 900;
|
||||
|
||||
auto len(s.length());
|
||||
unsigned long j(0);
|
||||
unsigned long i = 0;
|
||||
|
||||
for ( ; i < len-1; i++ ) {
|
||||
char str[3];
|
||||
str[0] = s[i];
|
||||
str[1] = s[i+1];
|
||||
str[2] = 0;
|
||||
|
||||
auto it(numTable.find(str));
|
||||
if (it != numTable.end()) {
|
||||
roman += it->second;
|
||||
i++;
|
||||
} else {
|
||||
remainder[j++] = s[i];
|
||||
remainder[j] = 0;
|
||||
}
|
||||
}
|
||||
if ( i < len ) {
|
||||
remainder[j++] = s[i];
|
||||
remainder[j] = 0;
|
||||
}
|
||||
for (i = 0; (i < remainder.length()) && (remainder[i] != 0); i++) {
|
||||
roman += singleRomanNumerals[remainder[i]];
|
||||
}
|
||||
|
||||
return roman;
|
||||
}
|
||||
};
|
||||
4
main.cpp
4
main.cpp
@@ -3,6 +3,7 @@
|
||||
#include "1-two-sum.cpp"
|
||||
#include "2-add-two-numbers.cpp"
|
||||
#include "9-palindrome-number.cpp"
|
||||
#include "13-roman-to-integer.cpp"
|
||||
|
||||
int main() {
|
||||
TwoSumSolution twoSumSolution;
|
||||
@@ -56,5 +57,8 @@ int main() {
|
||||
PalindromeNumberSolution p;
|
||||
std::cout << "Is 1 palindrome? " << p.isPalindrome(1) << std::endl;
|
||||
|
||||
RomanToIntegerSolution r;
|
||||
std::cout << "MCMXCIV = " << r.romanToInt("MCMXCIV") << std::endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user