#49 Roman to Integer
๐ฅ Roman to Integer ๐ฅ
Roman symbols
Symbol Value
I 1
V 5
X 10
L 50
C 100
D 500
M 1000
Example 1:
Input: s = "III";
Output: 3;
Example 2:
Input: s = "IX";
Output: 9;
Example 3:
Input: s = "LVIII";
Output: 58;
Explanation: (L = 50), (V = 5), (III = 3);
Example 4:
Input: s = "MCMXCIV"
Output: 1994
Explanation: M = 1000, CM = 900, XC = 90 and IV = 4.
์ฒดํฌํ ๋ถ๋ถ
- ๋ฌธ์์ ์ซ์๊ฐ์ธ cur, next ๋น๊ตํด์ add / subtract ๊ฒฐ์ ํ๊ธฐ
- ์กฐ๊ฑด๋ฌธ ํ์
- ๋ฐ๋ณต๋ฌธ ํ์
์ฝ๋ ์์ฑ
function romanToInt(s) {
const key = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
};
let result = [];
for (let i = 0; i < s.length; i++) {
if (key[s[i]] < key[s[i + 1]]) {
result.push(key[s[i + 1]] - key[s[i]]);
i++;
continue;
} else {
result.push(key[s[i]]);
}
}
return result.reduce((prev, current) => prev + current);
}
๋ ๋ค๋ฅธ ์ ๊ทผ๋ฒ
function romanToInt(s) {
const key = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
};
let result = 0;
for (let i = 0; i < s.length; i++) {
const cur = key[s[i]];
const next = key[s[i + 1]];
if (cur < next) {
result += next - cur;
i++;
} else {
result += cur;
}
}
return result;
}
WILT : What I Learned Today ๐ค
- ๋ชจ๋ ์กฐ๊ฑด์ ์ฒ๋ฆฌํด์ผํ๋ค๊ณ ์๊ฐํ๊ณ ์์ ํ๋๊น ์ฝ๋๋ฅผ ์์ฑํ๊ธฐ๊ฐ ์ด๋ ค์ ๋ค. ๊ฒฐ๊ตญ ํผ์ ์์ฑํ์ง ๋ชปํ๊ณ ๋ค๋ฅธ ์ฌ๋ ์ฝ๋๋ฅผ ์ฐธ๊ณ ํค์ ์์ฑํ๋๋ฐ ์์ธ ์ฝ๋๋ฅผ ๋จผ์ ์์ฑํ๋ ๊ทธ ์ธ์ ์ฝ๋๋ฅผ ๊ด๋ฆฌํ๊ธฐ๊ฐ ๋ฌด์ฒ ์ฌ์ ๋ค. ์ด๋ ๊ฒ ํ๋ฉด ๋ ๊ฒ ๊ฐ์๋ฐ ์๊ฐ์ด ๋ค๋ฉด baby step์ผ๋ก ๊ธฐ๋กํ๊ณ , ๋ ๋จ์ํ๊ณ ์ข์ ๋ฐฉ๋ฒ์ด ์์์ง ๊ณ ๋ฏผํด๋ณด์
continue
์break
์ ์ฐจ์ด์ ๋ํด ๋ช ํํ๊ฒ ์๊ฒ ๋์๋ค
break | ๋ฐ๋ณต๋ฌธ์ ์ข ๋ฃ |
---|---|
continue | ํ์ฌ ๋ฐ๋ณต์์์ ๋ช ๋ น์ ์ข ๋ฃํ๊ณ ๋ค์ ๋ฐ๋ณต์กฐ๊ฑด์ผ๋ก ๊ฑด๋๋ |
์ฐธ๊ณ
Roman Numeral To Integer - LeetCode Algorithm Solution + Code Vanilla Javascript