diff --git a/C++/Roman_to_Integer.cpp b/C++/Roman_to_Integer.cpp index a54fc83..4cbb293 100644 --- a/C++/Roman_to_Integer.cpp +++ b/C++/Roman_to_Integer.cpp @@ -1,60 +1,32 @@ -#include - -/*** 13. Roman to Intege (Easy)***/ - -/* -Symbol Value -I 1 -V 5 -X 10 -L 50 -C 100 -D 500 -M 1000 -*/ +// LeetCode Problem 13: Roman to Integer +// Author: Tanzeela Fatima (@Fatima-progmmer) +// Time Complexity: O(n) +// Space Complexity: O(1) class Solution { public: int romanToInt(string s) { - int current = 0, last =0; - int sum=0; - for(int i=0;ilast) - sum-=2*last; - last = current; - + unordered_map roman = { + {'I', 1}, {'V', 5}, {'X', 10}, {'L', 50}, + {'C', 100}, {'D', 500}, {'M', 1000} + }; + + int result = 0; + int prev = 0; + + // Traverse from right to left + for (int i = s.length() - 1; i >= 0; --i) { + int current = roman[s[i]]; + + if (current < prev) + result -= current; + else + result += current; + + prev = current; } - return sum; + + return result; } -}; \ No newline at end of file +}; +