Skip to content

Commit e1869bc

Browse files
solves roman to int
1 parent 41673a0 commit e1869bc

File tree

2 files changed

+43
-2
lines changed

2 files changed

+43
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@
55
|:--------:|------|:----------:|:--------:|
66
| 1 | [Two Sum](https://leetcode.com/problems/two-sum/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/TwoSum.java) |
77
| 7 | [Reverse Integer](https://leetcode.com/problems/reverse-integer/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/ReverseInteger.java) |
8-
| 9 | [PalindromeNumber](https://leetcode.com/problems/palindrome-number/) | Easy | |
9-
| 2 | []() | Easy | |
8+
| 9 | [PalindromeNumber](https://leetcode.com/problems/palindrome-number/) | Easy | [![Java](https://img.icons8.com/color/40/000000/java-coffee-cup-logo.png)](https://github.com/anishLearnsToCode/leetcode-algorithms/blob/master/src/PalindromeNumber.java) |
9+
| 2 | [Roman To Integer](https://leetcode.com/problems/roman-to-integer/) | Easy | |
1010
| 2 | []() | Easy | |
1111
| 2 | []() | Easy | |
1212
| 2 | []() | Easy | |

src/RomanToInteger.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// https://leetcode.com/problems/roman-to-integer/
2+
3+
import java.util.HashMap;
4+
import java.util.Map;
5+
import java.util.Scanner;
6+
7+
public class RomanToInteger {
8+
private static final Map<Character, Integer> romanNumerals = new HashMap<>();
9+
10+
static {
11+
romanNumerals.put('I', 1);
12+
romanNumerals.put('V', 5);
13+
romanNumerals.put('X', 10);
14+
romanNumerals.put('L', 50);
15+
romanNumerals.put('C', 100);
16+
romanNumerals.put('D', 500);
17+
romanNumerals.put('M', 1000);
18+
}
19+
20+
public static void main(String[] args) {
21+
Scanner scanner = new Scanner(System.in);
22+
String roman = scanner.next();
23+
System.out.println(romanToInt(roman));
24+
}
25+
26+
private static int romanToInt(String string) {
27+
int value = 0;
28+
for (int index = 0 ; index < string.length() ; index++) {
29+
if (index < string.length() - 1 && value(string.charAt(index)) < value(string.charAt(index + 1))) {
30+
value -= value(string.charAt(index));
31+
} else {
32+
value += value(string.charAt(index));
33+
}
34+
}
35+
return value;
36+
}
37+
38+
private static int value(char character) {
39+
return romanNumerals.get(character);
40+
}
41+
}

0 commit comments

Comments
 (0)