Romanto Integer Algorithm

The Roman to Integer Algorithm is a computational method designed to convert Roman numerals, which are a numeral system originating from ancient Rome, into their corresponding integer values. Roman numerals are represented by a combination of letters from the Latin alphabet, such as I, V, X, L, C, D, and M, which stand for 1, 5, 10, 50, 100, 500, and 1000, respectively. The algorithm works by iterating through the characters in a given Roman numeral string and adding up the integer values associated with each character, while also handling the specific rules and exceptions in Roman numeral notation, such as the subtraction principle (e.g., IX for 9 or XC for 90). To implement the Roman to Integer Algorithm, one needs to first create a mapping of Roman characters to their corresponding integer values. The algorithm then processes the input Roman numeral string from left to right, comparing the value of the current character with the value of the next character. If the value of the current character is less than that of the next character, it means that the subtraction principle applies, and the value of the current character should be subtracted from the total. Otherwise, the value of the current character is added to the total. This process is repeated for each character in the input string until the entire string has been processed, resulting in the final integer value.
class Solution {
public:
    int romanToInt(string s) {
		// Start typing your C/C++ solution below
		// DO NOT write int main() function
		int hash[256];
		hash['I'] = 1; hash['V'] = 5; 
		hash['X'] = 10; hash['L'] = 50; 
		hash['C'] = 100; hash['D'] = 500;
		hash['M'] = 1000;

		int result = 0;
		int num = 0;
		for (size_t i = 0; i < s.size(); i++) {
			if (hash[s[i]] == num) {
				num += hash[s[i]];
			} 
			else if (hash[s[i]] > num) {
				if (num) {
					result += hash[s[i]] - num;
					num = 0;
				}
				else num = hash[s[i]];
			}
			else {
				result += num;
				num = hash[s[i]];
			}
		}
		if (num) result += num;
		return result;
	}
};

LANGUAGE:

DARK MODE: