Created
September 15, 2022 10:23
-
-
Save ravichandrae/06ca290e982d7b2f7fdb87f13c107f24 to your computer and use it in GitHub Desktop.
Program to convert integers to roman and vice versa
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
import java.util.HashMap; | |
import java.util.Map; | |
public class RomanNumbers { | |
public static void main(String[] args) { | |
for (int i = 1; i <= 50; i++) { | |
String roman = intToRoman(i); | |
System.out.println(roman + " = " + romanToInt(roman)); | |
} | |
} | |
public static String intToRoman(int num) { | |
StringBuilder result = new StringBuilder(); | |
String[][] romanNumerals = {{"", "M", "MM", "MMM"}, | |
{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}, | |
{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}, | |
{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}}; | |
int[] romanInt = new int[]{1000, 100, 10, 1}; | |
for (int i = 0; i < romanInt.length; i++) { | |
result.append(romanNumerals[i][num / romanInt[i]]); | |
num = num % romanInt[i]; | |
} | |
return result.toString(); | |
} | |
public static int romanToInt(String romanNum) { | |
int result = 0; | |
Map<Character, Integer> romanToIntMap = new HashMap<>(); | |
romanToIntMap.put('M', 1000); | |
romanToIntMap.put('D', 500); | |
romanToIntMap.put('C', 100); | |
romanToIntMap.put('L', 50); | |
romanToIntMap.put('X', 10); | |
romanToIntMap.put('V', 5); | |
romanToIntMap.put('I', 1); | |
for(int i = 0; i < romanNum.length(); i++) { | |
int currentVal = romanToIntMap.get(romanNum.charAt(i)); | |
if(i < romanNum.length() - 1) { | |
int nextVal = romanToIntMap.get(romanNum.charAt(i + 1)); | |
if(currentVal < nextVal) { | |
result += nextVal - currentVal; | |
i++; | |
} else { | |
result += currentVal; | |
} | |
} else { | |
result += currentVal; | |
} | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment