Skip to content

Commit

Permalink
Add Leetcode 13. Roman to Integer
Browse files Browse the repository at this point in the history
  • Loading branch information
naco-siren committed May 3, 2020
1 parent dd77542 commit 0156d5a
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
42 changes: 42 additions & 0 deletions src/leetcode/LC_013/Solution13.java
@@ -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;
}
}
33 changes: 33 additions & 0 deletions src/leetcode/LC_013/Solution13Test.java
@@ -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"));
}
}

0 comments on commit 0156d5a

Please sign in to comment.