Created
April 20, 2022 21:09
-
-
Save Mavimarmara/5c6b37d4b4e376d3928b05f6458d401e to your computer and use it in GitHub Desktop.
Conversor de número romano para inteiro
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
/* | |
Objetivo: | |
Algoritmo para converter número romano para decimal. | |
Missing Test Case - 13. Roman to Integer of https://leetcode.com/problems/roman-to-integer/ | |
Regra de negócio: | |
Os números romanos possuem um limite de letras com números correspondentes, e a partir delas é feito um cálculo para descobrir os demais números. São elas: | |
Symbol Value | |
I 1 | |
V 5 | |
X 10 | |
L 50 | |
C 100 | |
D 500 | |
M 1000 | |
Para descobrir os demais valores: | |
quando a primeira letra é menor que a segunda, deve ser subtraído seus valores, por exemplo IV = 1 - 5 = 4. Do contrário, deve ser somado, por exemplo VI = 1 + 5 = 6. | |
Exemplo 1: | |
Input: s = "III" | |
Output: 3 | |
Explanation: III = 3. | |
Exemplo 2: | |
Input: s = "LVIII" | |
Output: 58 | |
Explanation: L = 50, V= 5, III = 3. | |
Exemplo 3: | |
Input: s = "MCMXCIV" | |
Output: 1994 | |
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4. | |
*/ | |
var romans = { | |
"I":1, | |
"V":5, | |
"X":10, | |
"L":50, | |
"C":100, | |
"D":500, | |
"M":1000 | |
} | |
var romanToInt = function(s) { | |
var decimal = 0; | |
for(var i = 0; i < s.length; i++){ | |
if(romans[s[i]] < romans[s[i+1]]){ //se o primeiro for menor que o segundo | |
decimal = decimal - romans[s[i]] | |
} else { | |
decimal = decimal + romans[s[i]] | |
} | |
} | |
return decimal | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment