You Might Need This

From programming_contest
Revision as of 04:23, 16 February 2015 by imported>Kmk21 (Created page with "=Roman Numerals= The first time i needed this in a contest, I thought about it, and ended up hardcoding the roman numerals from 1 to 50 by hand.....got "40" wrong, and missed...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Roman Numerals

The first time i needed this in a contest, I thought about it, and ended up hardcoding the roman numerals from 1 to 50 by hand.....got "40" wrong, and missed out on winning an SRM because of it (D2). Figured i'd never need it...and then it came up AGAIN...so finally I wrote some concise code to do it

/**
 * converts an integer to a roman numeral
 * @param n the number
 * @return a string of the roman numeral
 */
public String i2rn(int n) {
	String[] rn={"I","V","X","L","C","D","M"};
	String out="";
	while(n>1000){
		n-=1000;
		out+=rn[6];
	}
	for(int i=2;i>=0;i--){
		int temp=n/(int)Math.pow(10, i);
		n%=(int)Math.pow(10, i);
		if(temp%5==4){
			out+=rn[2*i];
			temp++;
		}
		if(temp>9){
			out+=rn[2*i+2];
			temp-=10;
		}
		if(temp>4)out+=rn[2*i+1];
		for(int j=0;j<temp%5;j++)out+=rn[2*i];
	}
	return out;
}
/**
 * converts a roman numeral string to an integer
 * @param n the input string
 * @return the integer
 */
public int rn2i(String n) {
	//2x0 100 500 4x0 1 2x0 50 1000 8x0 5 0 10
	int[] nr={0,0,100,500,0,0,0,0,1,0,0,50,1000,0,0,0,0,0,0,0,0,5,0,10};
	int ans=0;
	int[] t=new int[n.length()+1];
	for(int i=0;i<n.length();i++)t[i]=nr[n.charAt(i)-'A'];
	for(int i=0;i<n.length();i++){
		if(t[i+1]>t[i])ans-=t[i];
		else ans+=t[i];
	}
	return ans;
}