Last active
March 10, 2017 18:35
-
-
Save nitely/376e828b2f573d04d9a128d9257799e7 to your computer and use it in GitHub Desktop.
Lame JS puzzle #4
This file contains hidden or 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
/* | |
Translate roman numbers to decimals. If a roman letter/number is lesser than the next one substract, otherwise add. | |
*/ | |
// Time-Complexity = O(n) | |
// Space-Complexity = O(1) | |
const Romans = { | |
I: 1, | |
V: 5, | |
X: 10, | |
L: 50 | |
} | |
// LXIV -> 64 | |
function romanToDec(roman) { | |
if (!roman.length) | |
return 0; | |
let dec = 0; | |
let prevRoman = roman[0]; | |
// Skip first letter | |
for (let i = 1; i < roman.length; i++) { | |
// Test: | |
// 1. roman[i] == X, prevRoman == L, dec == 50 | |
// 2. roman[i] == I, prevRoman == X, dec == 60 | |
// 3. roman[i] == V, prevRoman == I, dec == 59 | |
if (Romans[prevRoman] < Romans[roman[i]]) | |
dec -= Romans[prevRoman]; | |
else | |
dec += Romans[prevRoman]; | |
prevRoman = roman[i]; | |
} | |
// 4. prevRoman == V, dec == 64 | |
dec += Romans[prevRoman]; | |
return dec; | |
} | |
console.log(romanToDec("LXIV")); |
This file contains hidden or 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
/* | |
Translate roman numbers to decimals. If a roman letter/number is lesser than the next one substract, otherwise add. | |
*/ | |
// Time-Complexity = O(n) | |
// Space-Complexity = O(1) | |
const Romans = { | |
I: 1, | |
V: 5, | |
X: 10, | |
L: 50 | |
} | |
// LXIV -> 64 | |
function _romanToDec(roman, i, acc) { | |
let prevRoman = Romans[roman[i - 1]]; | |
if (i == roman.length) | |
return acc + prevRoman; | |
if (prevRoman < Romans[roman[i]]) | |
acc -= prevRoman; | |
else | |
acc += prevRoman; | |
return _romanToDec(roman, i + 1, acc); | |
} | |
function romanToDec(roman) { | |
return _romanToDec(roman, 1, 0); | |
} | |
console.log(romanToDec("LXIV")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment