Skip to content

Add Roman To Integer conversion #720

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Mar 19, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions Conversions/RomanToInteger.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import java.util.*;

public class RomanToInteger {

private static Map<Character, Integer> map = new HashMap<>() {{
put('I', 1);
put('V', 5);
put('X', 10);
put('L', 50);
put('C', 100);
put('D', 500);
put('M', 1000);
}};

/**
* This function convert Roman number into Integer
*
* @param A Roman number string
* @return integer
*/
public static int romanToInt(String A) {

char prev = ' ';

int sum = 0;

int newPrev = 0;
for (int i = A.length() - 1; i >= 0; i--) {
char c = A.charAt(i);

if (prev != ' ') {
// checking current Number greater then previous or not
newPrev = map.get(prev) > newPrev ? map.get(prev) : newPrev;
}

int currentNum = map.get(c);

// if current number greater then prev max previous then add
if (currentNum >= newPrev) {
sum += currentNum;
} else {
// subtract upcoming number until upcoming number not greater then prev max
sum -= currentNum;
}

prev = c;
}

return sum;
}

public static void main(String[] args) {
int sum = romanToInt("MDCCCIV");
System.out.println(sum);
}
}