Preciso fazer um projeto para converter algarismos romanos em decimais e encontrei o seguinte método:
/**
* Author: Francisco Edmundo
*
**/
private int traduzirNumeralRomano(String texto) {
int n = 0;
int numeralDaDireita = 0;
for (int i = texto.length() - 1; i >= 0; i--) {
int valor = (int) traduzirNumeralRomano(texto.charAt(i));
n += valor * Math.signum(valor + 0.5 - numeralDaDireita);
numeralDaDireita = valor;
}
return n;
}
private double traduzirNumeralRomano(char caractere) {
return Math.floor(Math.pow(10, "IXCM".indexOf(caractere))) + 5 * Math.floor(Math.pow(10, "VLD".indexOf(caractere)));
}
Já fiz alguns testes e ele está funcionando, porém, não entendi exatamente o que ele faz e os parâmetros utilizados. Alguém pode me ajudar a “traduzir” esse código?
Está ai o codigo com uma explicação do que eu percebi do codigo. Qualquer duvida avisa
static int traduzirNumeralRomano(String texto) {
int n = 0;
int numeralDaDireita = 0;
for (int i = texto.length() - 1; i >= 0; i--) { //VAI ANALISAR CADA CARACTER DO TEXTO DE TRAS PARA A FRENTE
int valor = (int) traduzirNumeralRomano(texto.charAt(i));
n += valor * Math.signum(valor + 0.5 - numeralDaDireita); //ADICIONA AO TOTAL O VALOR OBTIDO, USANDO O
//METODO MATH.SIGNUM QUE VAI DECIDIR SE É POSITIVO
//OU NEGATIVO. O METODO MATH.SIGNUM RETORNA -1
//SE O NUMERO DA DIREITA FOR MAIOR, E 1 SE FOR MENOR.
numeralDaDireita = valor;
}
return n;
}
static double traduzirNumeralRomano(char caractere) {
//Math.floor(Math.pow(10, "IXCM".indexOf(caractere))) -> ELEVA O 10 Á POTENCIA DO SEGUNDO ARGUMENTO (MATH.POW)
// -> E ARREDONDA O NUMERO (MATH.FLOOR)
// -> POR EXEMPLO SE O CARACTER FOR 'I' O INDEX VAI SER 0
// -> 10 ELEVADO A 0 = 1
//
//5 * Math.floor(Math.pow(10, "VLD".indexOf(caractere))) -> CASO O CARACTER ESTEJA CONTIDO NA STRING "VLD"
// -> VAI FAZER O MESMO QUE NO ANTERIOR, MAS VAI MULTIPLICAR
// -> POR 5, VISTO QUE ESTAS LETRAS TEM VALOR 5,50 E 500.
return Math.floor(Math.pow(10, "IXCM".indexOf(caractere))) + 5 * Math.floor(Math.pow(10, "VLD".indexOf(caractere)));
}
Perfeito, esclareceu todas dúvidas! Muitíssimo obrigado 
Grande abraço.
1 curtida