Skip to content

Commit

Permalink
13.RomantoInteger
Browse files Browse the repository at this point in the history
  • Loading branch information
SE-MahmoudAbdelaal committed May 20, 2024
1 parent 8095d47 commit 6dc6fc9
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions leetcode/easy/RomantoInteger.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@

import java.util.HashMap;
import java.util.Map;

class Solution {
public int romanToInt(String s) {
Map<Character, Integer> map = new HashMap<>();
map.put('I', 1);
map.put('V', 5);
map.put('X', 10);
map.put('L', 50);
map.put('C', 100);
map.put('D', 500);
map.put('M', 1000);

int sum = 0;
int length = s.length();

for (int i = 0; i < length; i++) {
int currentVal = map.get(s.charAt(i));

// If the current value is less than the next value, it should be subtracted
if (i + 1 < length && currentVal < map.get(s.charAt(i + 1))) {
sum -= currentVal;
} else {
sum += currentVal;
}
}

return sum;
}
}

0 comments on commit 6dc6fc9

Please sign in to comment.