-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
8095d47
commit 6dc6fc9
Showing
1 changed file
with
32 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |