Last active
March 26, 2022 16:42
-
-
Save dgodfrey206/6abeccf2c89c5b582be8 to your computer and use it in GitHub Desktop.
HackRank
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string> | |
#include <algorithm> | |
#include <map> | |
#include <cassert> | |
namespace detail { | |
std::map<char, unsigned int> numerals = { {'I', 1}, {'E', 3}, {'V', 5}, {'X', 10}, {'L', 50} }; | |
unsigned int numeral_rank(char c) { | |
return numerals[c]; | |
} | |
bool isValidSpartanNumeralString(std::string const& sn) { | |
static std::string cs = "IEVXL"; | |
return std::all_of(sn.begin(), sn.end(), [&] (char c) { return cs.find(c) != std::string::npos; }); | |
} | |
} | |
int ConvertSpartanNumeral(std::string const& sn) { | |
using detail::numeral_rank; | |
using detail::isValidSpartanNumeralString; | |
if (!sn.size() || !isValidSpartanNumeralString(sn)) { | |
// invalid Roman numeral | |
return -1; | |
} | |
int total = numeral_rank(sn[0]); | |
if (sn.size() == 1) { | |
return total; | |
} | |
char prev = sn[0]; | |
bool lesser = false; | |
int rank = 1; | |
for (int i = 1; i < sn.size(); ++i) { | |
if (numeral_rank(sn[i]) < numeral_rank(prev)) { | |
lesser = true; | |
rank = -1; | |
} else if (lesser && (numeral_rank(sn[i]) == numeral_rank(prev))) { | |
rank = -1; | |
} | |
else { | |
lesser = false; | |
rank = 1; | |
} | |
total += rank * numeral_rank(sn[i]); | |
prev = sn[i]; | |
} | |
return total; | |
} | |
int main() { | |
assert(ConvertSpartanNumeral("II") == 2); | |
assert(ConvertSpartanNumeral("III") == 3); | |
assert(ConvertSpartanNumeral("VII") == 3); | |
assert(ConvertSpartanNumeral("VX") == 15); | |
assert(ConvertSpartanNumeral("VVV") == 15); | |
assert(ConvertSpartanNumeral("LVVV") == 35); | |
assert(ConvertSpartanNumeral("LIX") == 59); | |
assert(ConvertSpartanNumeral("VIIXL") == 63); | |
assert(ConvertSpartanNumeral("EXL") == 63); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment