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
dd77542
commit 0156d5a
Showing
2 changed files
with
75 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,42 @@ | ||
package leetcode.LC_013; | ||
|
||
import java.util.HashMap; | ||
import java.util.Map; | ||
|
||
/** | ||
* 13. Roman to Integer | ||
* | ||
* I 1 | ||
* V 5 | ||
* X 10 | ||
* L 50 | ||
* C 100 | ||
* D 500 | ||
* M 1000 | ||
*/ | ||
class Solution13 { | ||
int romanToInt(String s) { | ||
// Initialize a lookup table for each character | ||
final Map<Character, Integer> values = new HashMap<>(); | ||
values.put('I', 1); | ||
values.put('V', 5); | ||
values.put('X', 10); | ||
values.put('L', 50); | ||
values.put('C', 100); | ||
values.put('D', 500); | ||
values.put('M', 1000); | ||
|
||
// Iterate through each char | ||
int result = 0; | ||
int prev = 0; // Memorize previous digit's value | ||
for (int i = 0; i < s.length(); i++) { | ||
final int digit = values.get(s.charAt(i)); | ||
result += digit; | ||
if (digit > prev) | ||
result -= prev * 2; | ||
|
||
prev = digit; | ||
} | ||
return result; | ||
} | ||
} |
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,33 @@ | ||
package leetcode.LC_013; | ||
|
||
import org.junit.Test; | ||
|
||
import static org.junit.Assert.*; | ||
|
||
public class Solution13Test { | ||
|
||
@Test | ||
public void romanToInt_III() { | ||
assertEquals(3, new Solution13().romanToInt("III")); | ||
} | ||
|
||
@Test | ||
public void romanToInt_IV() { | ||
assertEquals(4, new Solution13().romanToInt("IV")); | ||
} | ||
|
||
@Test | ||
public void romanToInt_IX() { | ||
assertEquals(9, new Solution13().romanToInt("IX")); | ||
} | ||
|
||
@Test | ||
public void romanToInt_LVIII() { | ||
assertEquals(58, new Solution13().romanToInt("LVIII")); | ||
} | ||
|
||
@Test | ||
public void romanToInt_MCMXCIV() { | ||
assertEquals(1994, new Solution13().romanToInt("MCMXCIV")); | ||
} | ||
} |