Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Last active March 5, 2017 00:26
Show Gist options
  • Save shailrshah/d1eb018f114ac72b9b5efbd8ab4261ed to your computer and use it in GitHub Desktop.
Save shailrshah/d1eb018f114ac72b9b5efbd8ab4261ed to your computer and use it in GitHub Desktop.
Convert Roman numerals to Arabic ones
import java.util.HashMap;
import java.util.Random;
/**
* Created by shail on 03/04/17.
*/
public class Roman {
public static int toArabic(String roman) {
HashMap<Character, Integer> hm = new HashMap();
hm.put('M', 1000);
hm.put('D', 500);
hm.put('C', 100);
hm.put('L', 50);
hm.put('X', 10);
hm.put('V', 5);
hm.put('I', 1);
int a[] = new int[roman.length()];
for(int i = 0; i < roman.length(); i++)
a[i] = hm.get(roman.charAt(i));
int ans = 0;
for(int i = 0; i < a.length-1; i++) {
if(a[i+1] > a[i])
ans -= a[i];
else ans += a[i];
}
ans+=a[a.length-1];
return ans;
}
public static String toRoman(int arabic) {
StringBuilder sb = new StringBuilder();
int a[] = new int[]{1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String b[] = new String[]{"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
for(int i = 0; i < a.length; i++) {
while(arabic >= a[i]) {
arabic -= a[i];
sb.append(b[i]);
}
}
return sb.toString();
}
public static void main(String args[]) {
Random r = new Random();
for(int i = 0; i < 10; i++) {
int n = r.nextInt(1001);
String roman = toRoman(n);
int arabic = toArabic(roman);
System.out.println(n+" "+roman+" "+arabic);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment