Skip to content

Instantly share code, notes, and snippets.

@dineshrajpurohit
Last active August 29, 2015 14:05
Show Gist options
  • Save dineshrajpurohit/b3c81f996bb0d09362df to your computer and use it in GitHub Desktop.
Save dineshrajpurohit/b3c81f996bb0d09362df to your computer and use it in GitHub Desktop.
Number to Roman Conversion and Roman to Number conversion
package com.dinesh.tutorials;
class NumberAndRoman{
/**
* Converting the Numbers to Roman Numbers
*
**/
public static String convertToRoman(int num){
String rom = "";
while(num > 0){ //4894
if(num >= 1000){
num = num - 1000; // 3894 .. 2894 .. 1894 .. 894
rom += getRoman(1000);
}else if(num < 1000 && num >= 900){
num = num - 900;
rom += getRoman(900);
}else if(num < 900 && num >= 500){
num = num - 500;
rom += getRoman(500); //894 // 494
}else if(num < 500 && num >= 400){
num = num - 400; //94
rom += getRoman(400);
}else if(num < 400 && num >= 100){
num = num - 100;
rom += getRoman(100);
}else if(num < 100 && num >= 90){
num = num - 90; // 4
rom += getRoman(90);
}else if(num < 90 && num >= 50){
num = num - 50;
rom += getRoman(50);
}else if(num < 50 && num >= 40){
num = num - 40;
rom += getRoman(40);
}else if(num <40 && num >= 10 ){
num = num - 10;
rom += getRoman(10);
}else if(num < 10 && num >= 9){
num = num - 9;
rom += getRoman(9);
}else if(num < 9 && num >= 5){
num = num - 5; //3 //2 //1
rom += getRoman(5);
}else if(num < 5 && num >=4){
num = num - 4;
rom += getRoman(4);
}else if(num < 4 && num >=1){
num = num -1;
rom += getRoman(1);
}
}
return rom;
}
/**
*
* Helper to get the current Character in Roman form
*
*/
private static String getRoman(int n){
switch(n){
case 1000:
return "M";
case 900:
return "CM";
case 500:
return "D";
case 400:
return "CD";
case 100:
return "C";
case 90:
return "XC";
case 50:
return "L";
case 40:
return "XL";
case 10:
return "X";
case 9:
return "IX";
case 5:
return "V";
case 4:
return "IV";
case 1:
return "I";
default:
return null;
}
}
}
public class NumberAndRomanMain{
public static void main(String[] args){
for(int i=0; i< 20;i++){
int num = (int) (Math.random() * (4999 - 1)) + 1;
System.out.println("Roman Numeral for "+num+" is "+ NumberAndRoman.convertToRoman(num));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment