From b487d07376c38e15fd7d5091fe6ad9d2c0901f96 Mon Sep 17 00:00:00 2001 From: Tanzeela Fatima <149133736+Fatima-progmmer@users.noreply.github.com> Date: Thu, 7 Aug 2025 23:39:02 +0500 Subject: [PATCH] close(#508).cpp MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 🔢 Added C++ solution for LeetCode Problem 13: Roman to Integer - Used unordered_map for Roman numeral values - Traversed string from right to left - Time Complexity: O(n), Space Complexity: O(1) - Included comments and a sample test case Closes #508 --- C++/Roman_to_Integer.cpp | 80 +++++++++++++--------------------------- 1 file changed, 26 insertions(+), 54 deletions(-) diff --git a/C++/Roman_to_Integer.cpp b/C++/Roman_to_Integer.cpp index a54fc83f..4cbb2932 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 +}; +