Skip to content

Commit

Permalink
Add: leetcode/013.RomanToInteger
Browse files Browse the repository at this point in the history
  • Loading branch information
pixcai committed Jan 3, 2018
1 parent a8c9001 commit 9be3d83
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ Algorithms notes and code and leetcode solution by JavaScript
- [008.StringToInteger](leetcode/008.StringToInteger)
- [009.PalindromeNumber](leetcode/009.PalindromeNumber)
- [010.RegularExpressionMatching](leetcode/010.RegularExpressionMatching)
- [013.RomanToInteger](leetcode/013.RomanToInteger)
22 changes: 22 additions & 0 deletions leetcode/013.RomanToInteger/013.RomanToInteger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
function romanToInt(s) {
const roman = {
I: 1,
V: 5,
X: 10,
L: 50,
C: 100,
D: 500,
M: 1000
}
const N = s.length - 1
let result = roman[s[N]]

for (let i = 0, c, n; i < N; i++) {
c = roman[s[i]]
n = roman[s[i + 1]]
result += c < n ? -c : c
}

return result
}

13 changes: 13 additions & 0 deletions leetcode/013.RomanToInteger/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
### 代码实现
[013.RomanToInteger](013.RomanToInteger.js)

### 解题思路
罗马数字有一个特征:两个相邻的字符,如果左边比右边大,那么两个数应该相加,如果左边比右边小,那么这两个数应该相减。根据这个特点,可以写出下面的计算过程:
```js
for (let i = 0, c, n; i < N; i++) {
c = roman[s[i]]
n = roman[s[i + 1]]
result += c < n ? -c : c
}
```
依次将结果加上或减去罗马数的值,就将整个罗马数转换为了数字。

0 comments on commit 9be3d83

Please sign in to comment.