class Solution {
public int romanToInt(String s) {
int n = s.length(); // length of string
int sum = 0;
for (int i = 0; i < n; i++) {
char ch1 = s.charAt(i);
if ((i + 1) < n && getVal(ch1) < getVal(s.charAt(i + 1))) {
sum = sum - getVal(ch1);
} else {
sum = sum + getVal(ch1);
}
}
return sum;
}
public int getVal(char ch) { // values of all roman numerals
switch (ch) {
case 'I':
return 1;
case 'V':
return 5;
case 'X':
return 10;
case 'L':
return 50;
case 'C':
return 100;
case 'D':
return 500;
case 'M':
return 1000;
default:
return 0;
}
}
}
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)