Skip to content

Instantly share code, notes, and snippets.

@xynophon
Created January 27, 2015 07:03
Show Gist options
  • Select an option

  • Save xynophon/1ad539a01d2788e4dda1 to your computer and use it in GitHub Desktop.

Select an option

Save xynophon/1ad539a01d2788e4dda1 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
/**
* Created by xynophon on 15.1.27.
*/
public class roman_2_integer{
// I 1
// IV 4
// V 5
// IX 9
// X 10
// XL 40
// L 50
// XC 90
// C 100
// D 500
// M 1000
// MCMXCIX 1999
// I X C M
// IV 4, IX 9, XL 40, XC 90, CD 400, CM 900
public int char_2_num(char cha){
if(cha == 'I')return 1;
else if(cha == 'V')return 5;
else if(cha == 'X')return 10;
else if(cha == 'L')return 50;
else if(cha == 'C')return 100;
else if(cha == 'D')return 500;
else return 1000;
}
public int solution(String s){
int num = 0;
for(int i = 0; i < s.length(); i++){
num += char_2_num(s.charAt(i));
System.out.print(s.charAt(i)+" ");
if(i >= 1) {
if (s.charAt(i) == 'V' || s.charAt(i) == 'X') {
if (s.charAt(i - 1) == 'I') {
num -= 2*char_2_num(s.charAt(i - 1));
}
} else if (s.charAt(i) == 'L' || s.charAt(i) == 'C') {
if (s.charAt(i - 1) == 'X') {
num -= 2*char_2_num(s.charAt(i - 1));
}
} else if (s.charAt(i) == 'D' || s.charAt(i) == 'M') {
if (s.charAt(i - 1) == 'C') {
num -= 2*char_2_num(s.charAt(i - 1));
}
}
}
}
return num;
}
public static void main (String args[]){
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
roman_2_integer ri = new roman_2_integer();
System.out.println(ri.solution(line));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment