Created
September 20, 2016 13:39
-
-
Save ifndefdeadmau5/afba6a335e9f4c642909b0bd04cb867f to your computer and use it in GitHub Desktop.
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
// I = 1, V = 5, X = 10, L = 50, C = 100, D = 500, M = 1,000 | |
// I II III IV V VI VII VIII IX X | |
// XI XII XIII XV XVI | |
// XXI, MMXVI 2016 | |
// 800 -> DCCC | |
// 900 -> CM | |
// given roman numeral -> int | |
// function roman_to_int(roman_numeral) {} | |
// DC -> 600 | |
// | |
// DC = 600 | |
// CD = D - C = 400 | |
// III | |
// 1. Lager one come first( just add in order ) | |
// V I I I | |
// ^ | |
// V I I I | |
// ^ | |
// V I I I | |
// ^ | |
// V I I I | |
// ^ | |
// 2. Smaller one comes first( get subtract larger one from smaller one ) | |
// I V | |
// ^ | |
// I V | |
// ^ | |
// V - I | |
// // add a to b, subtract a from b, multiply a by b, divide a by b | |
// 3. XVI X + IV / X + VI | |
// X V I | |
// ^ | |
// X + V = 15 | |
// X V I = 16 | |
// 4. XIV | |
// 모든 경우의 수를 따지라 | |
// 보통 10분정도 계획을 설명하고 코딩 | |
// 1. prev < current | |
// 2. prev == current | |
// 3. prev > current | |
let RomanToInteger = romanStr => { | |
let roman = {}; | |
roman['I'] = 1; | |
roman['V'] = 5; | |
roman['X'] = 10; | |
roman['L'] = 50; | |
roman['C'] = 100; | |
roman['D'] = 500; | |
roman['M'] = 1000; | |
let sum = 0; | |
for (let i = 0; i < romanStr.length; ) { | |
if (roman[romanStr[i]] < roman[romanStr[i+1]]) { | |
sum += roman[romanStr[i+1]] - roman[romanStr[i]]; | |
i+=2; | |
} else if(roman[romanStr[i]] > roman[romanStr[i+1]]) { | |
sum += roman[romanStr[i+1]] + roman[romanStr[i]]; | |
i+=2; | |
} else { | |
// | |
} | |
} | |
console.log(sum); | |
} | |
RomanToInteger('XI'); | |
MCCCX | |
M C C C X End | |
result 0 1000 1000 1000 1300 1310 | |
buffer 1000 100 200 300 10 | |
// roman = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000, "": 0} | |
// def roman_to_int(roman_num): | |
// result = 0 | |
// buffer = 0 | |
// prev = "" | |
// for i, c in enumerate(roman_num): | |
// if c != prev: | |
// if roman[c] > roman[prev]: | |
// result -= buffer | |
// else: | |
// result += buffer | |
// buffer = 0 | |
// buffer += roman[c] | |
// prev = c | |
// result += buffer | |
// return result | |
// print roman_to_int("MCDXXIV") | |
` | |
// http://xkcd.com/287/ | |
// Depth first search / Recursion |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment