CS 3343/3341 Introduction to Algorithms |
Roman Numeral Conversion |
| Roman Numeral Conversion | |
|---|---|
| Java | C |
// Roman.java: convert to Roman Numerals
public class Roman {
public static void main(String[] args) {
int r = Integer.parseInt(args[0]);
System.out.println(trans(r));
}
static String trans(int r){
String[] s =
{"M","CM","D","CD","C","XC",
"L","XL","X","IX","V","IV","I"};
int[] u =
{1000, 900, 500, 400, 100, 90,
50, 40, 10, 9, 5, 4, 1};
String t = "";
for (int i = 0; i < 13; i++)
while (r >= u[i]) {
t += s[i];
r -= u[i];
}
return t;
}
}
| // roman.c: convert to Roman Numerals
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* trans(int , char* );
int main(){
int r;
scanf("%i", &r);
char* t = (char*)malloc(20);
t[0] = '\0';
printf("%s\n", trans(r, t));
}
char* trans(int r, char* t){
char* s[] =
{"M","CM","D","CD","C","XC",
"L","XL","X","IX","V","IV","I"};
int u[] =
{1000, 900, 500, 400, 100, 90,
50, 40, 10, 9, 5, 4, 1};
int i;
for (i = 0; i < 13; i++)
while (r >= u[i]) {
strcat(t, s[i]);
r -= u[i];
}
return t;
}
|
// RomanWeird.java: obscure conversion
public class RomanWeird {
public static void main(String[] args) {
int r = Integer.parseInt(args[0]);
System.out.println(trans(r));
}
static String trans(int r){
String s = "IVXLCDM", t = "";
int y = 1000, k = 13, x = 0;
while(k > 0){
if (k%4 == 1){
x = y;
y = x/10;
}
x -= y*(k%4-1)*(k%4-1);
while(r >= x){
r -= x;
if (k%2 == 0)
t += s.charAt((k-2)/4*2);
t += s.charAt((k+2)/2-1);
}
k--;
}
return t;
}
}
| // romanweird.c: obscure conversion
main(){
int r;
do{
scanf("%i",&r);
trans(r);
} while(r);
}
trans(int r){
char rom[] = "IVXLCDM";
int y = 1000, k = 13, x;
while(k > 0){
if(k%4 == 1){
x = y;
y = x/10;
}
x -= y*(k%4-1)*(k%4-1);
while(r >= x){
r -= x;
if( k%2 == 0)
putchar(rom[(k-2)/4*2]);
putchar(rom[(k+2)/2-1]);
}
k--;
}
putchar(10);
}
|
| Obfuscated Roman Numeral Conversion, First C source code ("roman.c"), then the C compiler command line (executable: "a.out") |
#include <stdio.h>
M I IV;XCIX XIX"%i",&IV);XL(IV);}V IV);}XL(I IV){CIX XC[]=L;I IX=VI*VI*VI*VI*VI-VI*VI-VI-VI,C=VI*VI-VI+CX,D;V C>VI-XI-XI){CXC CM==CX){D=IX;IX=D/(VI*XI+XI);}D-=IX*CD*CD;V IV>=D){IV-=D;CXC C%XI==XI-CX-CX)X XC[((C-XI)/VI)*XI]);X XC[(C+XI)/XI-CX]);}C--;}X VI*XI+XI);}
|