Created
June 10, 2023 16:11
-
-
Save fddemora/9c6455e28a464f7e8b75b220ff3408ba to your computer and use it in GitHub Desktop.
This file contains 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<iostream> | |
#include <string> | |
#include <unordered_map> | |
class Solution { | |
public: | |
int romanToInt(std::string s) { | |
int sum = 0; | |
int length = s.length(); | |
for(int i = 0; i < length; i++){ | |
// check for a size of 1 string | |
if (length == 1){ | |
sum += r[s[i]]; | |
} | |
// condition prevents index out of bounds | |
if(i == 0) continue; | |
int currentVal = r[s[i]], | |
prevVal = r[s[i-1]]; | |
char currentChar = s[i], | |
prevChar = s[i-1]; | |
// Subtraction instances are: I before V and X, X before L and C, C before D and M. | |
if((currentChar == 'V' || currentChar == 'X') && prevChar == 'I'){ | |
sum += currentVal - prevVal; | |
if(i != length - 2){i++;} | |
else { | |
sum += r[s[i+1]]; | |
break; | |
} | |
} | |
else if((currentChar == 'L' || currentChar == 'C') && prevChar == 'X'){ | |
sum += currentVal - prevVal; | |
if(i != length - 2){i++;} | |
else { | |
sum += r[s[i+1]]; | |
break; | |
} | |
} | |
else if((currentChar == 'D' || currentChar == 'M') && prevChar == 'C'){ | |
sum += currentVal - prevVal; | |
if(i != length - 2){i++;} | |
else { | |
sum += r[s[i+1]]; | |
break; | |
} | |
} | |
// condition where no subtraction conditions are met | |
else { | |
sum += i == length - 1 ? prevVal + currentVal : prevVal; | |
} | |
} | |
return sum; | |
} | |
private: | |
std::unordered_map<char, int> r = { | |
{'I', 1}, | |
{'V', 5}, | |
{'X', 10}, | |
{'L', 50}, | |
{'C', 100}, | |
{'D', 500}, | |
{'M', 1000}, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment