Skip to content

close(#508).cpp #509

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 26 additions & 54 deletions C++/Roman_to_Integer.cpp
Original file line number Diff line number Diff line change
@@ -1,60 +1,32 @@
#include <string>

/*** 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;i<s.length();i++){
switch(s[i]){
case 'I':
current = 1;
break;
case 'V':
current = 5;
break;
case 'X':
current = 10;
break;
case 'L':
current = 50;
break;
case 'C':
current = 100;
break;
case 'D':
current = 500;
break;
case 'M':
current = 1000;
break;
default:
break;
}
sum+=current;
/*
I can be placed before V (5) and X (10) to make 4 and 9.
X can be placed before L (50) and C (100) to make 40 and 90.
C can be placed before D (500) and M (1000) to make 400 and 900
*/
if(i!=0&&current>last)
sum-=2*last;
last = current;

unordered_map<char, int> 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;
}
};
};